In this tutorial you will learn the basic syntax of Bash. This is also useful for other UNIX shells.

In the following examples we can use > to distinguish a command from its output.

Table of Contents

Script structure

  • It’s recommended to put in the first line the “shebang” (#!) followed by the location of the Shell interpreter you want to use.
    #!/bin/bash
    
  • Script files need to have execute permissions.
    chmod +x script.sh
    

Variables

x=6                                                                        
item="some text"                                                           
  • Do not add spaces between =.

Reference a variable using $ and its name.

#!/bin/bash

item="some text"
echo $item
> ./script.sh
some text

If you want to output a text with several lines, you can use echo -e or printf.

y="One Line\nSecond Line"
printf $y

Arrays

x=(3 5 9)
y=(some_word, "some sentence")

echo ${x[0]}

x[0]=6

echo ${x[0]}

> ./script.sh
3
6
  • Print the number of items in an array.
    echo ${#x[@]}
    

Operators

Arithmetic

+ - * /
  • %: modulus.
  • **: power operator.
  • x++: increase x by one.

Bolean

  • Strings.
    =
    ==
    !=
    
  • Numbers.
    • -eq: equal to.
    • -gt: greater than.
    • -ge: greater than or equal to.
    • -lt: less than.
    • -le: less than or equal to.
    • -ne: not equal to.

Conditionals

if, elif, else

if [ $x -eq 6 ]
then echo "x is equal to 6"
else echo "x is not equal to 6"
fi

# or
if [ $x -eq 6 ]
then
echo "x is equal to 6"
else
echo "x is not equal to 6"
fi
if [ $y = "house" ]
then
echo "y is equal to house"
elif [ $y = "office" ]
then
echo "y is equal to office"
else
echo "y is not equal to house or office"
fi

Note that you need to add spaces between the operator.

case

case $x in
3) echo "x is equal to 3"
;;
6) echo "x is equal to 6"
;;
*) echo "x is not equal to 3 or 6"
esac

Loops

for

for i in $some_array
do
echo $i
done
for i in {1..30}
do
[ if $i = 15 ]
then break
# this will stop the loop, use 'continue' instead of 'break' to jump to the next loop item
fi
echo $i
done

while

i=5
while [ $i -gt 0 ]
do
echo $i
i=$(($i - 1))
done

Script arguments

./script.sh arg1 arg2

  • You can access these arguments using $ and 1 for the first argument, 2 for the second, etc.
    #!/bin/bash
    if [ $1 ]
    then
    first_argument=$1
    echo $first_argument
    fi
    
    > ./script.sh my_argument
    my_argument