In this tutorial we will learn simple bash script to prompt user yes / no for confirmation. It means when user run the script, it will first ask user to confirm by typing yes or no. Once user confirm it take appropriate action. Whereas in case, the user type apart of yes/no , it will print ‘invalid answer’ .
In this bash script we have added in-case sensitive choice by user , means no matter if user type yes or no in small or capital letter.
Steps to create the bash script
1. Create a bash script file , here in this example we have created file called
2. Now copy and paste the below given contents in
test.sh file. After this save and exit.
#!/bin/bash read -p "Do you want to run command 'uname -ar' ? (yes/no)" reply choice=$(echo $reply|sed 's/(.*)/L1/') if [ "$choice" = 'yes' ] then echo "Welcome you selected yes, wait for 3 seconds to get output"; sleep 3; uname -ar; elif [ "$choice" = 'no' ] then echo "You selected 'no', hence exiting in 3 seconds"; sleep 3 exit 0 else echo "invalid answer, type yes or no"; fi
3. Make the test.sh file executable .
chmod 700 test.sh
4. Now run the script test.sh
sh test.sh OR ./test.sh OR /GIVE/ABSOLUT/PATH/test.sh
Explaining the bash script
read -p "Do you want to run command 'uname -ar' ? (yes/no)" reply
In this line, read command will get value and store the value in variable called ‘reply’.
choice=$(echo $reply|sed 's/(.*)/L1/')
This line will convert all letters to small letters(see how we used sed command here). And new variable called ‘choice’ will keep the value of it.
(c) In rest of script we have used
If..Else statement with nesting.
There are many ways you can create this kind of bash script as per your requirement.