Mastering BASH Programming: Loops, Arrays, and Functions

School
Sheridan College**We aren't endorsed by this school
Course
SYST 18713
Subject
Computer Science
Date
Dec 12, 2024
Pages
54
Uploaded by kassemi
SYST18713Introduction to UNIX Operating SystemModule 10 UNIX - BASH Programming (Part 2)
Background image
BASH ProgrammingTopics:• Loops• Array Processing• The hereDocument• The Signals and trap Commandexec• Shell Functions
Background image
Looping LogicIteration 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 occursExamples:for loopwhile loop
Background image
The For LoopUse for to loop through a range of valuesIn the example, the loop repeats six timesfor USERS in john ellen tom becky eli jilldoecho $USERSdone
Background image
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
Background image
Looping: for..in statements- example 2The 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 structureIn 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.
Background image
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
Background image
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
Background image
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
Background image
Background image
Executing Control Structures at the Command Line
Background image
Using Wildcard Characters in a LoopThe [ ] wildcard characters can be useful in loopsExample:for file in chap[1234]; domore $filedone
Background image
Using Wildcard Characters in a Loop ExampleCreate 4 files called chap1,chap2,chap3,chap4 - example:$ ls >chap1$ ls -l>chap2$ who >chap3$ date >chap4Create script s1.sh:#!/bin/bash#s1.sh#using wildcard characters in a loop -examplefor file in chap[1234]; domore $filedoneTest the script file:$/bin/bash s1.sh
Background image
ganczarj@atlas:~/unix11$ for((i=1;i<=4;i++)); do echo "test"; donetesttesttesttest
Background image
Background image
#!/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)
Background image
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`doneechoTest the script file:$/bin/bash count.sh
Background image
The While Loopwhile continues to loop and execute statements as long as condition is trueExample:echo -n "Try to guess my favorite color: "read guesswhile [ "$guess" != "red" ]; doecho "No, not that one. Try again. "; read guessdone
Background image
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
Background image
Background image
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."
Background image
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."
Background image
Background image
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
Background image
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
Background image
Background image
Background image
Background image
#!/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
Background image
Case LogicCase logic structure simplifies selection of a match when you have a list of choicesUseful for user menusExample: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
Background image
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
Background image
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
Background image
Background image
Background image
$ echo ${#fruit[2]}7$ echo ${#fruit}6$ echo ${#fruit[*]}5$ echo ${fruit[2]}orange,
Background image
Background image
Background image
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
Background image
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
Background image
Background image
Background image
Background image
Background image
Background image
The trap Command
Background image
Background image
Background image
Background image
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
Background image
Background image
Background image
Background image
Background image
Background image