Linux Bash Scripting Tutorial


Control Statements

Bash supports following control statements

  • if
  • case
  • select

if statement

if/then construct tests whether the exit status of the list of commands is 0 (0 means "success"). If stament controls the execution of the commands

If statement syntax:

		if condition;
		then
		  comand(s)
		fi
	

if condition returns exit status 0, then command(s) will be executed.otherwise they're skipped.

if condition test can be done following ways,condition evaluates to true then exit status will be 0.commands between "then" and "fi" keywords will be executed, otherwise skipped.

   test shell command
if test 10 > 0; then 
echo "10 is greater" 
fi
						
    [ test command
if [ 10 > 0 ]; 
then 
	echo "10 is greater"; 
fi
   [[ extended test command or shell keyword
if [[ 10 > 0 ]]; 
	then 
		echo "10 is greater" 
	fi




[[ expression ]]
[[]] is same as test and [expression], except that additional operators are allowed. word splitting and file name exansion disabled.
but there is command substitution and parameter substitution
using [[]] can prevent may logical errors in program

Logical Operator
Logical OR operator
   ||
[[ op1 || op2 ]]op1 is false then it checks for op2,here either one should be true.
ex: no. is between 11 and 15
nirvana ~> num=12
nirvana ~> if [[ $num -gt 11 || $num -lt 15 ]]
Logical AND operator
   &&
[[ op1 && op2 ]]op1 is true then only it checks for op2,both should be true.
ex: no. is between 11 and 15
nirvana ~> num=12
nirvana ~> if [[ $num -gt 11 || $num -lt 15 ]]

If-else conditional Statement

if condition is true and exit status is 0 then commands following then keyword gets executed. otherwise else block gets executed.

If-else statement syntax:

		if condition;
		then
			command(s)
		else 
			command(s)
		fi
	

if-else example: using compound condition in if statement, to test whether numbers are negative(-ve) or positive(+ve).

		a=10;
		b=-1;
		if [[ "$a" -gt 0 && "$b" -gt 0 ]];
			then 
				echo "$a and $b are +ve numbers";
			else
				echo  "either  or both number (is/are) -ve ";

		fi;
	

If-elif conditional Statement

Multi level conditional check done using if-elif statement

If-elif statement syntax:

		if condition;
		then
			command(s)
		elif 
			command(s)
		else
			command(s)
		fi
	

if-elif example: using compound condition in if statement, to find maximum of three numbers

		a=10;
		b=-1;
		c=20;
		echo "Numbers are $a $b $c";
		if [[ "$a" -gt "$b" && "$a" -gt "$c" ]];
			then 
				echo "$a is maximum number";
			elif [[ $b -gt $c ]];
				then
				echo  "$b is maximum number";
			else
				echo  "$c is maximum number";

		fi;
	

Bash Comparing String Variables

String comparion operators
OperatorDescription
     == Operator    checks if two strings are equal, strings are case-sensitive in bash
     != Operator    checks if two strings are not equal, strings are case-sensitive in bash
     < Operator    checks if op1 is less than op2,
     > Operator    checks if op1 is greater than op2,
     -z Operator    tests operand or string length is 0,then return true
     -n Operator    tests operand or string length is non-zero,if non-zero returns true, exit status will be 0

String Comparison Examples

   Comparing strings for equality ==

Bash supports special syntax for testing a condition, programmer can use

[[ condition]] && 'true value'

[[ condition]] || 'false value'


  Following example city variable has 'new york' check for equality $city == 'new york' condition is True after && (logical and operator) command gets executed.

  Second example city variable has 'new york' check for equality $city == 'New york' condition is False after || (logical OR operator) command gets executed.

Note: Bash string comparisions are case sensitive
$ city='new york'

$ [[ $city == 'new york' ]] && echo 'new york'
new york
$ [[ $city == 'New york' ]] || echo 'new york'
new york

Converting a string to Upper to lower and Lower to Upper case



    Various ways to convert lower case to upper case or vice versa.

  • using Variable substitution
  • using tr command
Variable Substitution
	
		caret(^) symbol in variable substitution converts first letter to Upper Case
		
		$ city='London'
		$
		$ echo ${city^}
		London
	
		$ city='new york city'
		$
		$ echo ${city^}
		New york city

		First letter converted to Upper case.
		
	
	
		caret(^^) symbol in variable substitution converts all lower case letters to Upper Case
		
		$ city='London'
		$
		$ echo ${city^^}
		LONDON
	
		$ city='new york city, in this as many as 800 languages spoken'
		$
		$ echo ${city^^}
		NEW YORK CITY, IN THIS AS MANY AS 800 LANGUAGES SPOKEN


		All lower case letters converted to upper case
		
	
Using tr command
	
		$ echo "Hello Iam new to bash scripting" | tr [:lower:] [:upper:]
		HELLO IAM NEW TO BASH SCRIPTING
	

   [:lower:] and [:upper:] are character classes in Bash Regular expressions.
[:lower:] indicates lower case letters
[:upper:] indicates upper case letters


Using tr command and Here String
	
		$ var="Hello Iam new to bash scripting"  
		$ tr [:lower:] [:upper:]  <<<"$var"
		HELLO IAM NEW TO BASH SCRIPTING
	

   [:lower:] and [:upper:] are character classes in Bash Regular expressions.
[:lower:] indicates lower case letters
[:upper:] indicates upper case letters
Here String denoted with <<< is a simplest way or another way of supplying text to a command.

Bash case statement

Case Statement Syntax:

	case Expression in

		case1)  command(s);;
		case2)  command(s);;
		....
		caseN) command(s);;
	esac	
	

Bash Case Statement Example:

    Example:Display Day of the Week
#!/usr/bin/bash


day=`date +"%a"`
echo $day

case "${day}" in
        Mon) echo "Today is Monday pokers day";;
        Tue) echo "Today is Tuesday funday";;
        Wed) echo "Today is Wednesday pool game";;
        Thu) echo "Today is Thursday Gym workouts";;
        Fri) echo "Today is Friday Dreaming about Weekend";;
        Sat) echo "Today is Saturday weekend";;
        Sun) echo "Today is Sunday weekend";;
esac
	
    Example:Select [Yy]es [Nn]o [Aa]ll Using Case statement
#!/usr/bin/bash

        echo -e "Please enter [Yy]es [Nn]o [Aa]ll:"
        option=;
        read -n3 option;

        option=`echo "$option" | tr [:upper:] [:lower:]`

        case "$option" in

                y|yes) echo "You have selected Yes";;

                n|no)  echo  "You have selected No";;

                a|all) echo  "you have selected all";;

                *) echo "Invalid option";;
        esac

	

Bash select statement

select command is used to display menu style data

Syntax:

		select arg [in LIST];
		do
			respective-command;
		done
	

select command example:

#!/usr/bin/bash

select i;
do
	echo "You have selected : $i"
done

	

execute the script:

nirvana ~>bash sel2.sh  1 2 3
1) 1
2) 2
3) 3
#? 1
You have selected : 1
#? 2
You have selected : 2
#? 3
You have selected : 3
----------------------------------
nirvana ~>bash sel2.sh  "samsung"  "redme" "iphone"
1) samsung
2) redme
3) iphone
#? 1
You have selected : samsung
#? 2   
You have selected : redme
#? 3
You have selected : iphone
#? ^C

select command example: count number of files modified or created in a given month

select m in Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec exit
do
        case "${m}"
        in
		Jan) echo "${m} month files being  modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Feb) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Mar) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Apr) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		May) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Jun) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Jul) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Aug) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Sep) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Oct) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Nov) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		Dec) echo "${m} month files being modified  count:`ls -lt * | grep ${m}|wc -l` ";;
		exit) exit;;
        esac
done
     

ADS