E-learning module "Linux Basics"
Introduction to Bash Scripting
- There are multipe shells with different programming syntax. The most frequently used shell is possibly the bash.
- A shell script is a plain text file, often with the file extension
.sh(to make it easier for the user, not required by the operation system). - The text file always has to start with
#!/bin/bash(to set the shell to be used by the script). - The script can only be run directly, if the necessery execute permissions are set.
$var or ${var}→ Usage of a variable.#→ Comment.var=value→ Set the variablevartovalue.basename→ Remove the directory information from a path.dirname→ Returns the directory information of a path.read→ Allows to read values form standard input.
$0→ Name of the script including full path.$#→ Number of the provided parameters.$1,$2,…,$n→ The provided parameters.$*→ All parameters as a string.$?→ Contains the exit status after the end of a script.
Example 1: for-loop in a bash shell script:#! /bin/bashdummy=(one two three four) # Array!for u in ${dummy[*]}do echo $udone
Exercise: Try running this with $dummy[*] instead of ${dummy[*]}. What happens?
Explanation of Example 1:dummy=(one two three four)
defines the array dummy containing the four elements (strings) one, two, three and four. The elements are separated by blanks .${dummy[0]} denotes the first element of the array, ${dummy[1]} the second one, and so on.
Further reading: "Advanced Bash Scripting", slide 11.
The general structure of a do-loop is:for arg in listdo commanddone
In the example above, the command is executed for all elements u of the array dummy.
Further reading: "Advanced Bash Scripting", slide 26.
Example 2: if-condition:#! /bin/bashif [ -e ${HOME}/.bashrc ];then echo ".bashrc exists!"fi
Explanation of Example 2:$HOME or ${HOME} is an environment variable and denotes your home directory (and is explained here).if condition;then commandfi
is the simplest structure of an if-condition.
The condition is expressed by[ ]
Please note the blanks after [ and before ] ! They are necessary.
The condition[ -e filename ]
is true, if the file filename exists, otherwise it is false.
Further reading: "Advanced Bash Scripting", slides 24 and 25.
The content of this e-learning module is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license (CC BY-NC-SA 3.0 DE). |
