Multiple commands

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Linking CommandsHomePutting jobs in background →

You can build a sequences of commands using the ; character (operator) and syntax is:

command1 ; command2 ; commandN

OR

{ command1; command2 }

This way you can run commands one after the other. The following example, shell scripts display an error message if sufficient command line arguments are not passed (math.sh):

#!/bin/bash
a=$1
b=$3
op=$2
ans=0
 
# display usage
# run commands one after the other using ; chracter
[ $# -eq 0 ] && { echo -e "Usage: $0 num1 op num2\n\t $0 1 + 5";  exit 1; }
 
case $op in
	+)
		ans=$((( a+b )));;
	-)	
		ans=$((( a-b )));;
	/) 
		ans=$((( a/b )));;	
	\*|x) 
		ans=$((( a*b )));;
	*)				
		echo "Unknown operator."
		exit 2;;
esac		
echo "$a $op $b = $ans"

Save and close the file. Run it as follows:

chmod +x math.sh
./math.sh
./math.sh 1 + 5
./math.sh 10 \* 5

Without ; and && character (operator) joining multiple command the following one liner:

[ $# -eq 0 ] && { echo -e "Usage: $0 num1 op num2\n\t $0 1 + 5";  exit 1; }

would look like as follows:

if [ $# -eq 0 ] 
then
   echo -e "Usage: $0 num1 op num2\n\t $0 1 + 5"
   exit 1; 
fi

Examples

Use the watch command to monitor temp file (/tmp) system every 5 seconds:

watch -n 5 'df /tmp; ls -lASFt /tmp'
← Linking CommandsHomePutting jobs in background →