Lection 2: Bash scripting
Table of Contents
slide lection 2
slides Bash
home
1. Scripting parameters
A bash shell script can have parameters. The numbering you see in the script below continues if you have more parameters. You also have special parameters containing the number of parameters, a string of all of them, and also the process id, and the last return code. The man page of bash has a full list.
#!/bin/bash echo The first argument is $1 echo The second argument is $2 echo The third argument is $3 echo \$ $$ PID of the script echo \# $# count arguments echo \? $? last return code echo \* $* all the arguments
The shift statement can parse all parameters one by one. This is a sample script.
#!/bin/bash echo my name is $0 if [ "$#" == "0" ] then echo You have to give at least one parameter. exit 1 fi while (( $# )) do echo You gave me $1 shift done
2. Get script options with getopts
The getopts function allows you to parse options given to a command. The following script allows for any combination of the options a, b and c
#!/bin/bash while getopts ":abc" option; do case $option in a) echo received -a ;; b) echo received -b ;; c) echo received -c ;; *) echo "invalid option -$OPTARG" ;; esac done
You can also check for options that need an argument, as this example shows.
#!/bin/bash while getopts ":ab:c:" option; do case $option in a) echo received -a ;; b) echo received -b with $OPTARG ;; c) echo received -c with $OPTARG ;; :) echo "option -$OPTARG needs an argument" ;; *) echo "invalid option -$OPTARG" ;; esac done
3. Additional scripting elements
3.1. (())
The (( )) allows for evaluation of numerical expressions
> (( 42 > 33 )) && echo true || echo false > true > (( 42 > 1201 )) && echo true || echo false > false > var42=42 > (( 42 == var42 )) && echo true || echo false > true > (( 42 == $var42 )) && echo true || echo false > true > var42=33 > (( 42 == var42 )) && echo true || echo false > false
3.2. Case
You can sometimes simplify nested if statements with a case construct
#!/bin/bash # Job Helpdesk Advisor :-) echo -n "What job do you want ? " read job case $job in "devops") echo "Excellent" ;; "dev") echo "Good" ;; "test") echo "not bad." ;; "frontend") echo "Really???" ;; *) echo "Make your choise once more from: devops, dev, test and frontend" ;; esac
4. Functions
Shell functions can be used to group commands in a logical way.
#!/bin/bash function greetings { echo Hello World! echo and hello to $USER to! } echo We will now call a function greetings echo The end
4.1. Functions with parameters
A shell function can also receive paramaters
#!/bin/bash function plus { let result="$1 + $2" echo $1 + $2 = $result } plus 3 10 plus a b plus good 88
5. Read a file
You can read any file line by line in bash by using loop. Create a file named, ‘readfile.sh’ and add the following code to read an existing file named, ‘book.txt’.
#+/bin/bash file='book.txt' while read line; do echo $line done < $file
6. Variables
We can use variables as in any programming languages. Their values are always stored as strings, but there are mathematical operators in the shell language that will convert variables to numbers for calculations. There is no needed to declare variables. Just assign a value to its reference will create it
- The shell programming language does not type-cast its variables.
This means that a variable can hold number data or character data - Switching the TYPE of a variable can lead to confusion for the writer of the script or someone trying to modify it, so it is recommended to use a variable for only a single TYPE of data in a script
6.1. Double quotes
- When assigning character data containing spaces or special characters, the data must be enclosed in either single or double quotes.
- Using double quotes to show a string of characters will allow any variables in the quotes to be resolved
6.2. Sigle quotes
Using single quotes to show a string of characters will not allow variable resolution.
7. Types of variables
There are two types of variables:
- Local Variables
- Environmental Variables
7.1. Enviromental variables
They are set by the system and can usually be found by using the env command. Environmental variables hold special values, you can see a list of all of your environmental variables by using the env or printenv commands. In their default state, they should function exactly the same:
user@host$ printenv
This is the output:
SHELL=/bin/bash TERM=xterm USER=demouser LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca:... MAIL=/var/mail/demouser PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games PWD=/home/andres/Documents/personal/DevOps-project-lab/presentations/3rd_week LANG=en_US.UTF-8 SHLVL=1 HOME=/home/demouser LOGNAME=demouser LESSOPEN=| /usr/bin/lesspipe %s LESSCLOSE=/usr/bin/lesspipe %s %s _=/usr/bin/printenv
7.2. Special variables
Parameter | Description |
---|---|
$0 | Name of the current shell script |
$1-$9 | Positional parameters 1 through 9 |
${10} | Positional parameter 10 |
$# | The number of positional parameters |
$* | All positional paramenters, “$*” is one string |
$@ | All positional parameters, “$@” is a set of strings |
$? | Returns status of most recently executed command |
$$ | Proccess id of current process |
8. Command substitution
The backquote ` is different from the single quote ’, it is usede for command substitution: `command`
#!/bin/bash list=`ls -l` echo $list
9. Arithmetic evaluation
The let statement can be used to do mathematical functions.
An arithmetic expression can be evaluated by $[expression] or $((expression))
let x=10+2*4 echo $x echo "$((10+2*4))" val=$[10+2*4] echo "$[10+$val]"
Important:
Bash does not know how to work with floating point units
10. Conditional statements
The most basic form is:
if [ expression ]; then statements elif [ expression ]; then statements else statements fi
• the elif (else if) and else sections are optional • Put spaces after [ and before ], and around the operators and operands.
11. Expressions
An expression can be:
- String comparison
- Numeric comparison
- File operators and logical operators and it is represented by [expression]
11.1. String comparisons
Expression | Description |
---|---|
= or == | Compare if two strings are equal |
!= | Compare if two strings are not equal |
-n | Evaluate if string length is grater than zero |
-z | Evaluate if string length is equal to zero |
str1 < str2 | str1 is less than str2 |
str1 > str2 | str1 is greater than str2 |
11.2. Number comparisons
Expressions | Description |
---|---|
-eq | Compare if two numbers are equal |
-ge | Compare if one number is greater than or equal to a number |
-le | Compare if one number is less than or equal to a number |
-ne | Compare if two numbers are not equal |
-gt | Compare if one number is greater than another number |
-lt | Compare if one number is less than another number |
12. Control structures
12.1. Do-while
To execute commands in “command-list” as long as “expression” evaluates to true, this is the basic do-while syntax:
while [ expression ] do command-list done
#!/bin/bash COUNTER=0 while [ $COUNTER -lt 10 ] do echo “The counter is $COUNTER” let COUNTER=$COUNTER+1 done
Repeat until true:
myvar=0 while [ $myvar -ne 10 ]; do echo "$myvar" myvar=$(( $myvar + 1 )) done
Repeat until the value is false
myvar=0 until [ $myvar -eq 10 ] do echo $myvar myvar=$(( $myvar + 1 )) done
12.2. For
This is its basic sntax:
#!/bin/bash for x in one two three three four; do echo "number $x" done
And this is an example:
for myfile in /etc/r*; do if [ -d "$myfile" ] then echo "$myfile (dir)" else echo "$myfile" fi done