CSC 2500: Unix Lab Fall 2016 Control Statements in Shell Scripts: Decision Mohammad Ashiqur Rahman Department of Computer Science College of Engineering Tennessee Tech University
Agenda User Input Special Shell Variables Decision Control Statements if-then-else Statements Exit status test case Statements Lab 6: Working with Control Statements M. Ashiq Rahman, Tennessee Tech University 2
Input Toward Writing a Bash Script Prompting user Command line arguments Decision if-then-else case Repetition do-while, repeat-until for select Functions Traps The trap command allows to execute a command when a signal is received by the script. M. Ashiq Rahman, Tennessee Tech University 3
User Input Reading user input: read varname1 [varsname2...] read p "<Prompt>" varname1 [varsname2...] Each word entered by the user is stored in the variables The last variable gets rest of input line #!/bin/bash read -p Enter Your Name: " first last echo "First Name: $first" echo "Last Name: $last" $ bash read.sh Enter Your Name: Ashiq Rahman First Name: Ashiq Last Name: Rahman M. Ashiq Rahman, Tennessee Tech University 4
Special Shell Variables $0 - Name of the current shell script $1-$9 - Positional parameters 1 through 9 $# - The number of positional parameters $* - All positional parameters, $* is one string $@ - All positional parameters, $@ is a set of strings $? - Return status of most recently executed command $$ - Process id of current process $ set one two three four $ echo $* one two three four $ echo $# 4 $ echo $1 one $ echo $3 $4 The set command is used here to assign values to positional parameters. M. Ashiq Rahman, Tennessee Tech University 5
The if Statement if commands1 then commands2 fi if condition then statement fi if commands1; then commands2 fi if commands1; then commands2; fi commands is a list of commands. If commands1 (condition) succeeds, then commands2 (satement) executes. A command returns 0 when it succeeds Exit status test command M. Ashiq Rahman, Tennessee Tech University 6
Exit Status A command (can be a set of commands) issues a value to the system when it terminate, called an exit status. This value ranges from 0 to 255, indicates the success or failure of the command s execution. A value of zero indicates success, any other indicates failure. ashiq@ubuntu:~$ ls -d /usr/bin /usr/bin ashiq@ubuntu:~$ echo $? 0 ashiq@ubuntu:~$ ls -d /usr/trash ls: cannot access /usr/trash: No such file or directory ashiq@ubuntu:~$ echo $? 2 ashiq@ubuntu:~$ true ashiq@ubuntu:~$ echo $? 0 ashiq@ubuntu:~$ false ashiq@ubuntu:~$ echo $? 1 ashiq@ubuntu:~$ if true; then echo "It's true."; fi It's true. ashiq@ubuntu:~$ if false; then echo "It's true."; fi ashiq@ubuntu:~$ M. Ashiq Rahman, Tennessee Tech University 7
The test Command test is used as part of the conditional execution of shell commands. Syntax- Unusually two forms: test expression [ expression ] It evaluates expression and returns true or false (exit status) Note the spaces after the [ and before the ] M. Ashiq Rahman, Tennessee Tech University 8
Example: File Testing #!/bin/bash if test x $1 then echo File $1 is executable!" fi #!/bin/bash if [ w $1] then echo "File $1 is executable!" fi $ chmod u+x Test.sh $./Test.sh Test.sh File Test.sh is executable File Testing (using test) -d file: True if file is a directory -f file: True if file is a regular file -r file: True if file is readable -w file: True if file is writable -x file: True if file is executable -s file: True if length of file is nonzero There are more M. Ashiq Rahman, Tennessee Tech University 9
More if Statements if-then-else if commands1; then commands2 else commands3 fi If-then-elif- if commands1; then commands2 elif commands3; then commands4 else commands5 fi elif: else if More elifs possible M. Ashiq Rahman, Tennessee Tech University 10
Relational Operators Numeric Operators: Description Equal Not equal Greater than Less than Greater than or equal Less than or equal Operators -eg -ne -gt -lt -ge -le String Operators: Description Operators Equal = Not equal!= The string size is zero -z The string size is non-zero -n The string (str) is not empty str M. Ashiq Rahman, Tennessee Tech University 11
Example: If-elif #!/bin/bash read -p "Enter Income Amount: " income read -p "Enter Expenses Amount: " expense balance=`expr $income - $expense` if [ $balance -eq 0 ]; then echo "You are breaking even." elif [ $balance -gt 0 ]; then echo Great! You made a profit of: \$$balance." else echo Oops! You lost \$`expr 0 - $balance`." fi $./Elif.sh Enter Income Amount: 1000 Enter Expenses Amount: 900 Awesome! you made a profit of: $900. $./Elif.sh Enter Income Amount: 1000 Enter Expenses Amount: 1200 Oops! You lost $200. M. Ashiq Rahman, Tennessee Tech University 12
Logical Operators Logical or Boolean operators Description Operators Logical negation! Logical or -o ( ) Logical and -a (&&) If you use or &&, you will need to use [[ and ]] instead of [ and ]. #!/bin/bash read -p "Enter Income Amount: " income read -p "Enter Expenses Amount: " expense balance=`expr $income - $expense` if [[ $income -lt 0 $expense -lt 0 ]]; then echo Invalid input(s)! Please try again." elif [ $balance -eq 0 ]; then.. fi $./Elif.sh Enter Income Amount: -100 Enter Expenses Amount: -20 Invalid input(s)! Please try again. M. Ashiq Rahman, Tennessee Tech University 13
The case Statement A decision based on multiple choices or options Syntax: case word in pattern1) commands1;; pattern2) commands2;;......... patternn) commandsn;; esac The pattern is checked against the word for a match The pattern may also contain: * - zero or more characters? - any one character [ ] - a character class Regular expressions can be used Multiple patterns can be listed using M. Ashiq Rahman, Tennessee Tech University 14
#!/bin/bash Example: case read -p "Enter the vulnerability score (0 10): " score case $score in [0 3]) echo Good! The system is at low risk." ;; [4 6]) echo The system is at medium risk." ;; [7 9]) echo Oops! The system is at high risk." ;; 10) echo Oops! The system is at high risk." ;; *) echo Wrong input! exit 1;; esac $./Case.sh Enter the vulnerability score (0 10): 8 Oops! The system is at high risk. $./Case.sh Enter the vulnerability score (0 10): 12 Wrong input! M. Ashiq Rahman, Tennessee Tech University 15
Lab 06 Objective: Shell variables Simple if decision statements The read command File redirection Homework: You will write a script named planner.sh. Your program asks the user some questions and construct a plan for the user by writing information to the user's.plan file in the user's home directory. M. Ashiq Rahman, Tennessee Tech University 16
Lab 06: Homework Submission Rename the shell script file to <FirstNameInitial><LastName>_planner.sh Submission Deadline: Friday, October 07, 2016 Submission Site: ilearn A Dropbox folder named Homework 06 Submission Content: The shell script file <FirstNameInitial><LastName>_planner.sh. M. Ashiq Rahman, Tennessee Tech University 17
Lab 06: Lab Practice Write a script which will ask for a username. If there is not a file that exists with the name username_age, the script will prompt the user s age. The script will then make sure that the user is old enough to use this program. Then it will write the age of the user to a file with the name username_age. If the file already exists, it will just display the age of the user. M. Ashiq Rahman, Tennessee Tech University 18
THANKS Acknowledgement: - https://www.howtoforge.com/tutorial/linux-shell-scripting-lessons-3/ - http://linuxcommand.org/lc3_wss0080.php - https://www.tutorialspoint.com/unix/unix-basic-operators.htm M. Ashiq Rahman, Tennessee Tech University 19