You are on page 1of 26

Shell Scripting II

Ing. Ruben Cordova


Advanced Networks Research Lab.
Pontifical Catholic University of Peru

1
Outline

 Bash programming II
 Loops
 For
 While
 Control
 Case statement
 Null device
 Wildcard
 Local and global variables
 Conditional execution
 I/O redirections and file descriptors
 Functions
 User interaction

2
Bash Scripting: Loops

 Repeat particular instruction(s) until condition is satisfied


 Two types:
 For
 While
 Control loops:
 break: terminate execution of loop
 continue: exit current execution (continue loop)
 Nested loops:
 Exit nested loops: break/continue [level]

3
Bash Scripting: For loop

 'for' syntax
for {variable_name} in {list}
do
    execute one of each item in list until end
done
 {list}: defined as ‘{start...end}’ or ‘seq start end’
 “for” statement can use following C-syntax
for (( expr1; expr2; expr3 ))

4
Previous Activities:

 Script to print first ten even numbers


 Script to make a division using addition and subtraction. Also, indicate remain

5
Bash Scripting: Even number example

 #list=`seq 1 20`
#for i in list

for i in {1..20}
do
r=`expr $i % 2`

if [ "$r" -eq 0 ]
then
echo "$i“
fi
done
 for (( i=1; i<=$1; i++ ))
do
r=`expr $i % 2`

if [ "$r" -eq 0 ]
then
echo "$i“
fi
done

6
Bash Scripting: Division example

 ddo=$1
dor=$2
q=0
r=0

for i in {1..100000}
do
if [ "$ddo" -ge "$dor" ]
then
q=`expr $q + 1`
ddo=`expr $ddo - $dor`
else
r=$ddo
break
fi
done

echo "Quotient: $q“


echo "Remaining: $r"
7
Bash Scripting: While loop

 'while' syntax
while [ condition ]
do
    execute one of each item in list until condition is false
done
 Condition in “while” statement follow same syntax that conditionals

8
Activity 1

 Rewrite activities from slide 5 using while loop


 Print first 10 even numbers.
 Division as addition and subtraction

9
Activity 1: Solutions

 Print first 10 even numbers.

echo -n "Ingrese el numero de numeros pares a imprimir: “


read num
i=1
while [ "$i" -le "$num" ]
do
e_num=`expr 2 \* $i`
echo $e_num
i=`expr $i + 1`
done

10
Activity 1: Solutions

 Division as addition and subtraction

ddo=$1
dor=$2
q=0

# Division:
# While dividend is greater or equal than divisor, increase in 1 the quotient.
# When dividend is lower than divisor, set is value as remainder

while [ $ddo -ge $dor ]


do
ddo=`expr $ddo - $dor`
q=`expr $q + 1`
done

r=$ddo

echo "Dividend: $1“


echo "Divisor: $2“
echo "Quotient: $q“
echo "Remainder: $r"

11
Bash Scripting: Case statement

 Alternative to multilevel ‘if-elif-else’ statement


 Match several values against one variable
 Syntax
case $var_name in
pattern1) command1;;
pattern2) command2
command3;;

*) command;;
esac

12
Activity 2

 Use case statement to select the language of a greeting


ES: Hola
EN: Hellow
GE: Hallo
PR: Oi!

13
Activity 2: Solution

 echo "----------------“
echo -e "[ES] Spanish\n[EN] English\n[GE] German\n[PR] Portuguese“
echo "----------------“
echo -n “Select language: “
read lang

case $lang in
"ES") echo "Hola";;
"EN") echo "Hello";;
"GE") echo "Hallo";;
"PR") echo "Oi!";;
*) echo “Cannot understand that language";;
esac

14
Bash Scripting: /dev/null

 Send unwanted output of command


 /dev/null: device that discards information written to it
 Syntax
command > /dev/null
 Example: compare outputs of following commands (remember redirection?)
 date
 date > /dev/null

15
Bash Scripting: Wildcards

 ‘*’: matches any string or group of characters


 ‘?’: matches any single character
 […]: matches any of the enclosed characters
 Example: what do you get if execute the following commands?
 ls –lh *s
 ls –lh D[eo]*
 ls –lh ?[ueo]*

16
Bash Scripting: Local and Global
variables
 Normally all variables are local (actual shell)
 Load another copy of shell: ignore all old shell’s variables
 Copy shell variable to new shell: ‘export’ command

* ~/.bashrc (non-login shell) and ~/.bash_profiles (login shell)


More information: man bash, INVOCATION section

17
Bash Scripting: Conditional execution

 command1 && command2: command 2 is executed if and only if command1


returns an exit status of zero
 command1 || command2: command 2 is executed if and only if command1
returns a non-zero exit status
 Example: execute both sequences of commands
 ls -lh Documentos/ && mail -s "Ejecucion condicional de comandos"
ruben.cordova@pucp.pe <<< “Directorio $(echo `pwd`)/Documentos existe“
 ls -lh Documents/ || mail -s "Ejecucion condicional de comandos"
ruben.cordova@pucp.pe <<< " Directorio $(echo `pwd`)/Documents existe"

18
Bash Scripting: I/O redirection and file
descriptors
 Redirectors: send output of command to file or read input from file
 cat ‘>’ input_file: output redirection
 sort ‘<’input_file: input redirection*
 In Linux systems, keyboard and screen are treated as files

Standard File File Descriptor Use Example


stdin 0 as Standard input Keyboard
stdout 1 as Standard Screen
output
stderr 2 as Standard error Screen

19
Bash Scripting: I/O redirection and file
descriptors
 Every Linux program has three files associated with it (opened by shell when starting program)
 FD 0 and 1 already seen
 command > file: redirect output of command (shown in stdout) to file
 FD 2: print error on screen (redirection: ‘2>’)
 command 2> file: redirect error output of command (shown in stderr) to file
 Show usage error of script/command in FD 2: ‘1>&2’
 Example:

case $1 in
"-d") date;;
"-h") hostname;;
"-u") uname -a;;
"") echo "Error: args: must specify an argument" 1>&2;; #Double quotation marks
*) echo "Error: usage: file_descriptors.sh -arg" 1>&2;;
esac
20
Bash Scripting: Functions

 Reuse of code
 Syntax:
function-name()
{
command1
command2

command
return
}

21
Bash Scripting: Functions

 Functions need to be declared BEFORE code that use them


 Do not return a value to caller
 Return its exit status value
 Based on last executed if not specified
 Return value
 Set variable (persist in caller)
 Command substitution: var=$(func_name)

22
Bash Scripting: Function Example

 even_numbers()

{
for i in $(echo `seq 1 $1`)
do
echo $(echo `expr 2 \* $i`)
done
}

odd_numbers()
{
for i in $(echo `seq 1 $1`)
do
echo $(echo `expr 2 \* $i - 1`)
done
}

total_number()
{
echo -n "Total numbers to show: “
read num
}

23
Bash Scripting: Function Example

 (Continuation)

while [ 1 ]
do
echo -e -n "[1] Print even numbers\n[2] Print odd numbers\n[9] Exit\nChoose an option: “
read opt

case $opt in
"1") total_number
even_numbers "$num";;
"2") total_number
odd_numbers "$num";;
"9") echo "Bye!“
break;;
*) echo "Not valid option";;
esac
done
24
Bash Scripting: User Interface and
Dialogs
 Interaction with users
 Use of ‘read’ command
 Decision based on answer
 case
 if-elif-else
 for/while

25
References

1. Vivek G. Gite. Linux Shell Scripting Tutorial


http://www.freeos.com/guides/lsst/index.html
2. Mendel Cooper. Advanced bash-Scripting Guide
http://tldp.org/LDP/abs/html/index.html
3. Mitch Frazier. Returning Values from Bash Functions
http://www.linuxjournal.com/content/return-values-bash-functions

26

You might also like