How to use IF in bash shell script with example
If condition with sample bash script
Now, you can use the if statement to test a condition. If command the general syntax is as follows:
if condition
then
command1
command2
...
commandN
fi
If given condition is true than the command1, command2..commandN are executed. Otherwise script continues
If the condition is true then the following commands get executed. If not the script continues with the next command.
Let’s have a practical example for this.
Open a text editor and create the script called check.sh:
#!/bin/bash
read -p "Enter a password" password
if test "$password" == "LinuxAdmin"
then
echo "Password verified."
fi
Save and close the file. Give executable permission to check.sh to do so type following command:
chmod +x check.sh
./check.sh
Sample Outputs:
Enter a password : LinuxAdmin
Password verified.
Let’s check what if we give wrong password - Run it again:
./check.sh
Sample Output:
Enter a password : ServerAdmin
the script does not print any message and script will go to the next statement. Here is another example
We can expand the script by displaying one another additional message in the result.
check.sh:
#!/bin/bash
read -p "Enter your password " password
if test $password == LinuxAdmin
then
echo "Your password is accepted – Thank you.! "
fi
if test $password != LinuxAdmin
then
echo "The entered password is wrong – Sorry.! "
fi
Save and close the file. Run it as follows:
./check.sh
Sample Outputs:
Enter your password : LinuxAdmin
Your password is accepted – Thank you.!
Run it again enter wrong password.
./check.sh
Sample Outputs:
Enter your password : ServerAdmin
The entered password is wrong – Sorry.!
Also read :
Tips to create super strong passwords easely
Change your password right now - Heartbleed
Write one liner Batch Script to Take Your File Backup
7 Types of Dangerous Virus
2 Software to Keep Your Passwords Safe and Secure
Comments
Post a Comment