Aerosol Posted December 8, 2014 Report Posted December 8, 2014 Like many other modern high level programing languages or code interpreters, Linux shell has capability to use conditional statements. Often when writing a computer code, theres a need to perform different actions based on various logical decisions. For this purpose, it is possible to use conditional statements. Syntax of If/else statement: if condition_is_truethen execute commandselseexecute commandsfi Example below demonstrates simple if/else statement structure. If condition is satisfied, instructions after "then" syntax will be procesed, otherwise code or commands after "else" statement are executed: LinuxBox#vi my_script.sh #!/bin/bash # Condition check if/else statement number=5 if no=5; then echo "Number is 5 !" else echo "Number is not 5 !" fi :wq! LinuxBox# LinuxBox# ./my_script.sh Number is 5 !We can use simple If/else statement for example in a script that checks if directory exists: LinuxBox# vi my_script.sh #!/bin/bash # simple if/else directory existence check directory="./myScripts" #check if directory exists if [ -d $directory ]; then echo "Directory exists !" else echo "Directory does not exists !" fi LinuxBox# ./my_script.sh Directory does not exists ! LinuxBox# mkdir myScripts LinuxBox# ./my_script.sh Directory exists !While structure (loops)The while construction allows for repetitive execution of code or list of commands, as long as the command controlling the while loop executes successfully (exit status of zero). Syntax of While structure: while condition_is_truedoexecute these commandsdone This example shows while syntax. While loop keeps looping as long as counter is greater than 0: LinuxBox# vi my_script.sh #!/bin/bash # simple while looop script COUNT=5 while [ $COUNT -gt 0 ]; do echo Value of counter is: $COUNT let COUNT=COUNT-1 done LinuxBox# ./my_script.sh Value of counter is: 5 Value of counter is: 4 Value of counter is: 3 Value of counter is: 2 Value of counter is: 1(Loop use Relational Operators in "[while condition]" to check for how long script has to loop. To see more about Relational Operators check this tutorial ) This example use while loop to get the right user input. Until user selects the right answer, script will keep (looping) repeating itself: LinuxBox# vi my_script.sh #!/bin/bash # while loop # Declare variable choice and assign value 0 choice=0 # Print to stdout echo "1. Shell" echo "2. Scripting" echo "3. ITTutorials" echo -n "Please enter a choice [1,2 or 3]? " # Loop while the variable choice is equal 0 while [ $choice -eq 0 ]; do # read user input read choice if [ $choice -eq 1 ]; then echo "Your choice is: Bash" else if [ $choice -eq 2 ] ; then echo "Your choice is: Scripting" else if [ $choice -eq 3 ] ; then echo "Your choice is: ITTutorials" else # user haven't entered the right choice so we'll ask the question again echo "Please make a choice between 1-3 !" echo "1. Bash" echo "2. Scripting" echo "3. ITTutorials" echo -n "Please choose a word [1,2 or 3]? " # and reset choice to 0 choice=0 fi fi fi done LinuxBox# ./my_script.sh 1. Shell 2. Scripting 3. ITTutorials Please enter a choice [1,2 or 3]? 3 Your choice is: ITTutorials LinuxBox#(Unless user enters integer value between 1-3, script will keep repeating itself.) Until loopLike the while loop, until loop is used for the same purpose of repetitive execution of code. Only difference is that condition that's controling loop is opposite. Loop will keep "looping" as long as the condition remains false, or in this case until it reaches value of defined counter: Syntax of Until loop: until [false]doexecute commandsdoneLinuxBox# vi my_script.sh #!/bin/bash # simple untill loop script, will keep looping until counter reaches value of 6 COUNT=0 # bash until loop until [ $COUNT -gt 5 ]; do echo Value of count is: $COUNT let COUNT=COUNT+1 done Select commandThe select command is often used for creating an interactive terminal menus. Syntax of Select statement:select varName in listdocommand1command2............commandNdoneExample of script with interactive terminal menu using select statement: LinuxBox# vi my_script.sh #!/bin/bash # select statement PS3='Choose one word: ' # bash select select word in "linux" "shell" "scripting" "ittutorials" do echo "The word you have selected is: $word" # Break, otherwise we'll have endless loop break doneexit 0 ( PS stands for prompt statement. It is shell's environment variable, and default prompt string used by select is "#?". It can be changed by re-defining PS3, so Select can display the string stored in PS3 when it is ready to read the user's selection like in the example.) Case statementShell case statement is similar to switch statement in C and some other programing languages. It checks the Case condition, and controls the flow of the program. It can be used to test simple values like integers and characters. Syntax of Case statement:case expression indopattern1) execute commands ;;pattern2) execute commands ;;....patternN) execute commands ;;esacExample script with case statement: LinuxBox# vi my_script.sh #!/bin/bash # simple Case example script echo "What is your preferred programming / scripting language" echo "1) bash" echo "2) php" echo "3) C++" echo "4) C" echo "5) Exit" read user_choice; case $user_choice in 1) echo "You selected bash";; 2) echo "You selected php";; 3) echo "You selected C++";; 4) echo "You selected C";; 5) exit esac LinuxBox# ./my_script.sh What is your preferred programming / scripting language 1) bash 2) php 3) C++ 4) C 5) I do not know ! 1 You selected bashShell FunctionsAs in many other programming languages, usage of functions is also possible in shell scripting. Functions are used to group pieces of code in a more logical way, to enable calling that code anywhere inside the script and using it multiple times. Declaring a function is done by using "function" keyword with the name of that function. For example, function my_func { my_code }. Inside "{" and "}" goes code that will be executed every time the function is called. Calling a function is simple as writing function's name. Example of script that uses functions: LinuxBox# vi my_script.sh #!/bin/bash # script that uses functions function addition { A=3 B=5 result=`expr $A + $B` exho "$A + $B = $result" exit } function hello { echo "Just saying Hello from function." } hello addition LinuxBox# ./my_script.sh Just saying Hello from function. 3 + 5 = 8 Arithmetic ComparisonUsing relational operators we can easily compare numeric values. These operators would not work for string values unless their value is numeric. To see more about relational operators check Linux shell opertors tutorial. Comparing 2 numbers using relational operators: LinuxBox# vi my_script.sh #!/bin/bash # comparing 2 integer numbers echo "Enter 1st umber:" read 1st echo "Enter 2nd umber:" read 2nd if [ $1st -eq $2nd ]; then echo "Both numbers are equal" elif [ $1st -gt $2nd ]; then echo "1st is greater then 2nd number" else echo "2nd is greater then 1st number" fi LinuxBox# ./my_script.sh Enter 1st umber: 22 Enter 2nd umber: 5 1st is greater then 2nd numberSource Quote