If Statements and Exit

Conditions and Decision Making

if: Used as part of a conditional statement, in which based on one or more conditions the script will take certain action(s)

Syntax

if [ <condition> ]
then
	run_this_comand
fi

if: initiates the if statement

[]: Encapsulates the condition

then: Runs the following commands if the condition is true

fi: Ends the if statement

if and else

else can be used to run a command if an expression returns false

Syntax

if [ <condition> ]
then
	run_this_command
else
	run_this_command
fi

Combining Tests with && and ||

&&: Will run the provided commands if both conditions returns true

||: Will run the provided commands if at least one condition returns true

Creating Conditions

Built-In Variables and Command Expansions

Environment variables can be called within an expression:

if [ $USER != 'sysadmin' ]
then
	echo "You are not sysadmin!"
	exit
fi

Commands can be called within an expression by using $(command):

if [ $(whoami) = 'sysadmin' ]
then
	echo "You are sysadmin!"
fi

Lists and Loops

Lists

Syntax

list=(1 2 3 4)

# To list all items
echo ${list[@]}

# To call on a single list item
echo ${list[0])
echo ${list[1])

for Loops

Syntax

for <item> in <list>
do
	run_this_command
done

The following uses command expansion to show file properties for each file in a directory:

for file in $(ls)
do
	ls -lah $file
done

The following displays a number if it is a 1 or 4 within an list of numbers:

for num in {0..5}
do
	if [ $num = 1 ] || [ $num = 4 ]
	then
		echo $num
	fi
done

for Loops for System Administrators

Looping Packages

The following runs through a list of packages and checks if they are installed:

# Define packages list
packages=(
    'nano'
    'wget'
    'net-tools'
)

# loop though the list of packages and check to see if they are installed

for package in ${packages[@]}

do
    if [ $(which $package) ]
    then
        echo "$package is installed at $(which $package)."
    else
        echo "$package is not installed."
    fi
done

Looping Users

The following searches each users’ home directory for files containing the .sh extension, then prints a confirmation message:

# Search each user's home directory for scripts and provide a formatted output.
for user in $(ls /home)
do   
    for item in $(find /home/$user -iname '*.sh')
    do
        echo -e "Found a script in $user's home folder! \\n$item"
    done
done

Looping Permissions

The following checks if the files in a directory have the executable permission bit, and applies it if not already applied

# loop through scripts in my scripts folder and set permissions to executable
for script in $(ls ~/scripts)
do
    if [ ! -x ~/scripts/$script ]
    then
        chmod +x ~/scripts/$script
    fi
done

-x: Test that checks if the file has the executable permission bit applied

Leave a Reply

Your email address will not be published.