All shell script files start with #!/bin/bash line. This is called a shebang. This tells which interpreter should call to parse the script. Example of a shell script file:
1 2 3
#!/bin/bash
echo"hello, world"
Commenting
Any line begin with # is a comment.
1 2 3 4
#!/bin/bash
# This is a comment echo"hello, world"# This is a comment too
Here documents
Feed text as it is into the standard input including whitespace and quotation marks. Here documents have the following form:
1 2 3
command << token text token
For example following script will feed the whole text to cat. As a result whole text will be printed as it is into the shell.
# A program to do some usefull things with unix tools
TOOL=shell
case $TOOL in shell) echo "Throw into the sea." ;;
strip) echo "Jump into the water." ;;
time) echo "Jump in a black hole" ;;
sleep) echo "Now do a interstellar travel" ;;
*) echo "You are in a limbo" ;; esac
Looping
For Loop
1 2 3 4 5 6 7 8 9 10 11
#!/bin/bash
# Structure of the for loop # # for $variable in sequence; do # something with the variables # done
for f in $(ls); do echo$f done
While Loop
Executes while a condition is true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/bin/bash
# Structure of while loop # # while [ Expression ]; do # do something # done
number=0
while [ $number -lt 10 ]; do echo"Number: $number" number=$((number + 1)) done
Until
Executes until a condition is true.
1 2 3 4 5 6
number=0
until [ $number -gt 10 ]; do echo"Number $number" number=$((number + 1)) done
break and continue
Like any other programming languages break and continue statement can be applied in a loop to break the loop or continue the loop on some condition.
Array
Arrays are defined as array_name=(0 "name" 4) where array_name is the name of the array an 0, name are the elements of the array. Array can be subscripted and iterated in following way:
1 2 3 4 5 6 7 8 9 10
array_name=(0 "name" 4)
# Print first element of the array echo${array_name[1]}
# Iterating through the array # Print all the elements of the array for elem in${array_name[@]}; do echo$elem done
Functions
Structure of a function in shell script is following:
1 2 3 4 5 6 7
func_name () { commands return }
# Function call func_name
Example:
1 2 3 4 5 6 7 8
#!/bin/bash
get_hostname () { echo$HOSTNAME return }
get_hostname
Functions must be defined before they are called.
In shell all variables are global. A local variable can be created using local command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#!/bin/bash
ID=0
get_hostname () { local ID ID=1 echo$HOSTNAME echo"local ID before calling function: ${ID}" return }
echo"global ID before calling function: ${ID}" get_hostname echo"global ID after calling function: ${ID}"