Shell Syntax


Comprehensive shell scripting cheatsheet covering Bash (Bourne Again Shell), which is one of the most common shells:

# Comments start with #

# Variables
VAR="value"
echo $VAR

# Command substitution
CURRENT_DIR=$(pwd)
CURRENT_DIR=`pwd`  # older syntax

# Arithmetic
RESULT=$((5 + 3))

# Conditional statements
if [ "$VAR" = "value" ]; then
    echo "Condition met"
elif [ "$VAR" = "other" ]; then
    echo "Other condition met"
else
    echo "No condition met"
fi

# Loops
for i in 1 2 3 4 5; do
    echo $i
done

for file in *.txt; do
    echo "Processing $file"
done

while [ $VAR -lt 10 ]; do
    echo $VAR
    VAR=$((VAR + 1))
done

# Functions
my_function() {
    echo "Argument 1: $1"
    echo "All arguments: $@"
    return 0
}

# Call function
my_function arg1 arg2

# File test operators
[ -e file.txt ]  # file exists
[ -d /path ]     # directory exists
[ -f file.txt ]  # regular file exists
[ -r file.txt ]  # file is readable
[ -w file.txt ]  # file is writable
[ -x file.txt ]  # file is executable

# String operations
STRING="Hello, World!"
echo ${#STRING}  # length of string
echo ${STRING:7}  # substring from index 7
echo ${STRING/World/Universe}  # replace World with Universe

# Arrays
ARRAY=(item1 item2 item3)
echo ${ARRAY[0]}  # first item
echo ${ARRAY[@]}  # all items
echo ${#ARRAY[@]}  # number of items

# Input/Output
echo "Enter your name:"
read NAME
echo "Hello, $NAME!"

# Redirections
command > output.txt  # redirect stdout to file
command 2> error.txt  # redirect stderr to file
command &> all.txt    # redirect both stdout and stderr

# Pipes
command1 | command2  # pipe output of command1 to command2

# Command line arguments
echo "Script name: $0"
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"

# Exit status
command
echo $?  # prints exit status of last command

# Case statement
case "$VAR" in
    pattern1)
        command1
        ;;
    pattern2)
        command2
        ;;
    *)
        default_command
        ;;
esac

# Arithmetic comparison
[ $VAR -eq 5 ]  # equal
[ $VAR -ne 5 ]  # not equal
[ $VAR -lt 5 ]  # less than
[ $VAR -le 5 ]  # less than or equal
[ $VAR -gt 5 ]  # greater than
[ $VAR -ge 5 ]  # greater than or equal

# String comparison
[ "$STRING1" = "$STRING2" ]   # equality
[ "$STRING1" != "$STRING2" ]  # inequality
[ -z "$STRING" ]  # true if string is empty
[ -n "$STRING" ]  # true if string is not empty

# Logical operators
[ condition1 ] && [ condition2 ]  # AND
[ condition1 ] || [ condition2 ]  # OR
[ ! condition ]  # NOT

# Special variables
echo "PID of current script: $$"
echo "Last background PID: $!"

# Debugging
set -x  # turn on debugging
set +x  # turn off debugging

# Here document
cat << EOF > output.txt
This is a
multi-line
text
EOF

# Subshell
(cd /tmp && echo "Current dir: $PWD")
echo "Back to: $PWD"