LinuxUncategorized

BASH scripting with conditional logic

IF/THEN statements

#!/bin/bash
echo "What would you like to see?
Todays date (d)
Currently logged in users (u)
The contents of the / directory (r)

Enter your choice(d/u/r)--> "
read ANSWER
if [ $ANSWER = "d" –o $ANSWER = "D" ]
	then echo "Today’s date is: "
	date
elif [ $ANSWER = "u" –o $ANSWER = "U" ]
then
	echo "The people logged into the system include:"
	who
elif [ $ANSWER = "r" –o $ANSWER = "R" ]
then
	echo "The contents of the / directory are:"
	ls /
fi

CASE statements

#!/bin/bash
echo "What would you like to see?
Todays date (d)
Currently logged in users (u)
The contents of the / directory (r)

Enter your choice(d/u/r)--> "
read ANSWER
case $ANSWER in
	d | D ) 
		echo "Today’s date is: "
		date
		;;
	u | U ) 
		echo "The people logged into the system include:"
		who
		;;
	r | R ) 
		echo "The contents of the / directory are:"
		ls /
		;;
	*) echo –e "Invalid choice! \a"
		;;
esac

WHILE statements

#!/bin/bash
COUNTER=0
while [ $COUNTER –lt 7 ]
do
	echo "All work and no play makes Jack a dull boy" 
	COUNTER=`expr $COUNTER + 1`
done

Leave a Reply