Nesting ifs
Sometimes, you must check for several situations in your script code. For these situations, you can nest the if-then
statements:
To check if a logon name is not in the /etc/passwd
file and yet a directory for that user still exists, use a nested if-then
statement. In this case, the nested if-then
statement is within the primary if-then-else
statement's else
code block:
$ ls -d /home/NoSuchUser/
/home/NoSuchUser/
$
$ cat test5.sh
#!/bin/bash
# Testing nested ifs
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
echo "The user $testuser exists on this system."
else
echo "The user $testuser does not exist on this system."
if ls -d /home/$testuser/
then
echo "However, $testuser has a directory."
fi
fi
$
$ ./test5.sh
The user NoSuchUser does not exist on this system.
/home/NoSuchUser/
However, NoSuchUser has a directory.
$
The script correctly finds that although the login name has been removed from the /etc/passwd...