Bash Scripting – Exploring more about the if-then-else Statement
Other Learning Articles that you may like to read
Free Courses We Offer
Paid Training Courses we Offer
In the if-then statement, you have only one option for whether a command is successful. If the command returns a non-zero exit status code, the bash shell just moves on to the next command in the script. In this situation, it would be nice to be able to execute an alternate set of commands. That’s exactly what the if-then-else statement is for.
if command then commands else commands fi
When the command in the if statement line returns with a zero exit status code, the commands listed in the then section are executed, just as in a normal if-then statement. When the command in the if statement line returns a non-zero exit status code, the bash shell executes the commands in the else section.
$ cp test3.sh test4.sh $ $ nano test4.sh $ $ cat test4.sh #!/bin/bash # testing the else section # testuser=NoSuchUser # if grep $testuser /etc/passwd then echo “The bash files for user $testuser are:” ls -a /home/$testuser/.b* echo else echo “The user $testuser does not exist on this system.” echo fi $ $ ./test4.sh The user NoSuchUser does not exist on this system. $