←back

Bash scripting cheatsheet

Bash shebang

Commenting

# this symbol makes everything after it on a line a comment

Variables

Builtin shell variables

$0             #Name of this shell script itself.
$1             #Value of first command line parameter (similarly $2, $3, etc)
$#             #In a shell script, the number of command line parameters.
$*             #All of the command line parameters.
$-             #Options given to the shell.
$?             #Return the exit status of the last command.
$$             #Process id of script (really id of the shell running the script)

File redirection and Piping

Input

Arithmetic

result=`expr $1 + 2`
result2=`expr $2 + $1 / 2`
result=`expr $2 \* 5`               #note the \ on the * symbol

Conditionals

Comparisons

Booleans

!     #not
-a    #and
-o    #or

Numerical comparisons

-eq == equal to 
-ne ≠ (not equal to)
-gt > greater than
-ge >= greather than or equal to
-lt < less than
-le <= less than or equal to
< less than
<= less than or equal to ((within double parenthesis))
> greater than ((within double parenthesis))
>= greater than or equal to ((within double parenthesis))
= equal to, including for strings, e.g. ```if [ "$a" = "$b" ]```

STRING COMPARISONS

== is equal to
!= is NOT equal to
< less than (ascii-betically)
> greater than (ascii-betically)
-z string is null
-n string is not null

Example comparisons

if [ "$VAR1" = "$VAR2" ]; then
    echo "expression evaluated as true"
else
    echo "expression evaluated as false"
fi
case "$C" in
"1")
    do_this()
    ;;
"2" | "3")
    do_what_you_are_supposed_to_do()
    ;;
*)    #fallback default case
    do_nothing()
    ;;
esac

Looping

### FOR loop
for i in 1 2 3 4 5    # can also be written for i in {1..5} or {start..end..increment}
do
    echo "Welcome $i times"
done

Example - Basic text menu

#!/bin/bash
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
        if [ "$opt" = "Quit" ]; then
        echo done
        exit
    elif [ "$opt" = "Hello" ]; then
        echo Hello World
    else
        clear
        echo bad option
    fi
done

WHILE loop

while [ condition ]
do
    command
done
### UNTIL loop
until [ condition ] # executes until condition = true
do
    command
done

Functions

function e {
    echo $1
}

e Hello #will echo Hello when called

Debugging

#!/bin/bash -x Adding -x to the shebang produces output information

Additional shell features

$var           #Value of shell variable var.
${var}abc      #Example: value of shell variable var with string abc appended.
#              #At start of line, indicates a comment.
var=value      #Assign the string value to shell variable var.
cmd1 && cmd2   #Run cmd1, then if cmd1 successful run cmd2, otherwise skip.
cmd1 || cmd2   #Run cmd1, then if cmd1 not successful run cmd2, otherwise skip.
cmd1; cmd2     #Do cmd1 and then cmd2.
cmd1 & cmd2    #Do cmd1, start cmd2 without waiting for cmd1 to finish.
(cmds)         #Run cmds (commands) in a subshell.