BASH ProgrammingTopics:• Loops• Array Processing• The hereDocument• The Signals and trap Command• exec• Shell Functions
Looping Logic•Iteration •Often, we need to repeat the same set of commands a number oftimes, which we do by putting the block of code inside a loop. •In looping logic, a control structure repeats until a specific condition exists or some action occurs•Examples:•for loop•while loop
The For Loop•Use for to loop through a range of values•In the example, the loop repeats six timesfor USERS in john ellen tom becky eli jilldoecho $USERSdone
The For Loopvi aloop.shfor USERS in john ellen tom becky eli jilldoecho $USERSdonesh aloop.shjohnellentombeckyelijillfor USERS in john ellen tom becky eli jilldoecho $USERSdone
Looping: for..in statements- example 2•The control structures for loops to examine in the following examples are while, for, and foreach.•Create and examine the following script . •Note the use of the for control structure•In order to run the script, create the data file called animalList$ cat > animalListlionmonkeytiger•...and so one, one animal per line. End the input using Control+Dkey combination.
Looping: for..in statements- example 2#!/bin/bash#e4.sh#for..in statementsecho "You can see the following animals in our zoo: "for animal in `cat animalList`doecho $animaldone
Looping: for..in statements- example 3Create a script file mem1.sh:#!/bin/bash#mem1.sh#for..in example 3echo "The things I like to do include:"for myHobbies in read, ski, "collect stamps", rundoecho $myHobbiesdone
Looping: for..in statements- example 3Run the script file mem1.sh:$/bin/bash mem1.shYou should get results:The things I like to do include:read,ski,collect stamps,run
Executing Control Structures at the Command Line
Using Wildcard Characters in a Loop•The [ ] wildcard characters can be useful in loops•Example:for file in chap[1234]; domore $filedone
Using Wildcard Characters in a Loop Example•Create 4 files called chap1,chap2,chap3,chap4 - example:$ ls >chap1$ ls -l>chap2$ who >chap3$ date >chap4•Create script s1.sh:#!/bin/bash#s1.sh#using wildcard characters in a loop -examplefor file in chap[1234]; domore $filedone•Test the script file:$/bin/bash s1.sh
ganczarj@atlas:~/unix11$ for((i=1;i<=4;i++)); do echo "test"; donetesttesttesttest
#!/bin/bash#count2.sh#expr converts its arguments to numbers, adds them, converts the results#to characters, and echoes them to the standard outputnumber=0while [ "$number" -lt 10 ]doecho "$number"number=`expr $number + 1`doneechoNumerical test:-lt (less than)-eq (equal)-gt (greater than)-ge (greater than or equal to)-ne (not equal)For string comparisons use:= (equal)!= (not equal)
Numerical test:-lt (less than)-eq (equal)-gt (greater than)-ge (greater than or equal to)-ne (not equal)For string comparisons use:= (equal)!= (not equal)•Create a script file count.sh:#!/bin/bash#count.shnumber=0while [ "$number" -lt 10 ]doecho "$number"number=`expr $number + 1`doneecho•Test the script file:$/bin/bash count.sh
The While Loop•while continues to loop and execute statements as long as condition is true•Example:echo -n "Try to guess my favorite color: "read guesswhile [ "$guess" != "red" ]; doecho "No, not that one. Try again. "; read guessdone
•Example:#!/bin/bash#s2.sh#while loop example - guess colorecho "Try to guess my favorite colour: "read guesswhile [ "$guess" != "red" ]; doecho "No, not that one. Try again."; read guessdoneecho "Correct, my favorite colour is " $guess
Until…do…done… -exampleCreate a file unitl2.sh - example: nano until2.sh#!/bin/bash#until2.sh#until...do...done...-examplesecretname=joename=nonameecho "Try to guess the secret name!"echountil [ "$name" = "$secretname" ]doread nameecho "Your guess" $nameecho "is incorrect. Try again"doneecho "very good."
Until…do…done… -exampleCreate a file unitl3.sh - example: nano until3.sh#!/bin/bash#until3.sh#until...do...done...-examplesecretname=joename=nonameecho "Try to guess the secret name!"echountil [ "$name" = "$secretname" ]doread -p "Enter your guess: " namedoneecho "very good."
Break and continue - exampleCreate a script brk.sh –example: nano brk.sh#!/bin/bash#brk.sh#continue break - examplesfor index in 1 2 3 4 5 6 7 8 9 10doif [ $index -le 3 ] ; thenecho "continue"continuefi#echo $index#if [ $index -ge 8 ] ; thenecho "break"breakfidoneTest the script:bash brk.shcontinuecontinuecontinue45678break
2.This alternative demonstrates the utilization of continue and break statements:#!/bin/bash#l11b.sh# since we are making an assignment which will always# evaluate to true, we have created an endless loopwhile [ repeat=y ]doecho "What is your name?"read nameif [ $name = "Ellen" -o $name = "ellen" -o $name = "ELLEN" ]thenecho "Hello, $name"elseecho "Hello, $name. You are not Ellen"firead -p "Again? (Type c to continue, followed by Enter) " input# when the user selects c to continue, the continue command will# start the next iteration of the loop. Otherwise, the break command# will execute and exit the loop.if [ $input = c ]thencontinuefibreakdone
#!/bin/bash#command_menu.sh#sample command menuecho " COMMAND MENU"echo "a. Current date and time"echo "b. Users currently logged in"echo "c. Name of the working directory"echo "d. Contents of the working directory"echo "Enter a, b, c, or d:"read answerechocase "$answer" ina)date;;b)who;;c)pwd;;d)ls -l;;*)echo "There is no selection: $answer";;esac
Case Logic•Case logic structure simplifies selection of a match when you have a list of choices•Useful for user menus•Example:echo -n "Enter your favorite color: "; read colorcase "$color" in"blue") echo "As in My Blue Heaven.";;"yellow") echo "As in the Yellow Sunset.";;"red") echo "As in Red Rover, Red Rover.";;"orange") echo "As in Autumn has shades of Orange.";;*) echo "Sorry, I do not know that color.";;esac
Exercise : case statements •Create a file called e3.sh. •Note the syntax: the value stored in $letter is compared to the pattern A, B, and C; •if one of them matches, the corresponding block is executed; •the double semi-colon indicates the end of the block. •If there is no match found, the default (or catchall) block is executed;•note the catchall pattern is an asterisk and is listed last
Exercise : case statements –sample solution#!/bin/bash#e3.sh#Case statementsread -p "Enter A, B, or C: " lettercase $letter inA)echo "You entered A";;B)echo "You entered B";;C)echo "You entered C";;*)echo "You did not enter A, B, or C";;esac
ExamplesCreate a script birthday.sh:#!/bin/bash#birthday.sh#A here document examplegrep -i "$1" <<+Max June 22Barbara February 3Darlene May 8Helen March 13Zach January 23Nancy June 26+grep –i ignore case $1 denotes the first command line argument passed (positional parameter)<<+ + -the here document
Test the script:/bin/bash birthday.sh ZachZach January 23/bin/bash birthday.sh JuneMax June 22Nancy June 26/bin/bash birthday.shMax June 22Barbara February 3Darlene May 8Helen March 13Zach January 23Nancy June 26
The trap Command
•Create a script file exec_demo.sh (nano exec_demo.sh):#!/bin/bash#exec_demo.sh#example of exec whoexec dateecho "This echo command is never executed "•Test the script:/bin/bash exec_demo.sh