Looping On Bash Scripting

There is serveral method to do looping in bash script, just like C or any other language it's for and while do. I will demonstrate two of them in this post.

The fist time create a file with .sh extention and write down this script. This script will resulting count down the number from 10 to 0 and at the end will execute some command. At the moment I just give echo messages at the end of the proccess.

#!/bin/bash 
for num in $(seq 10 -1 0)
do 
        echo "$num second until blastoff" 
        sleep 1
done
echo BLASTOFF

If you done then give permission to this file with executable permission so the file can be executed and run your script.
[sysadmin@localhost bin]$ 2for.sh 
10 second until blastoff
9 second until blastoff 
8 second until blastoff 
7 second until blastoff 
6 second until blastoff 
5 second until blastoff 
4 second until blastoff 
3 second until blastoff 
2 second until blastoff 
1 second until blastoff
0 second until blastoff
BLASTOFF

The second example will be while and do. At this example the prompt will ask you to quit or continue the some task. You can use while do to do this so if the input parameter doesn't math then the prompt will be execute again until the parameter is math then the prompt will quit.

#!/bin/bash
while true 
do
        read -p "Do you want to quit (y/n) ? " answer
        if [ "$answer" == "y" ]
        then
                break
        fi
done

Give the executable permission and run the script
[sysadmin@localhost bin]$ while.sh
Do you want to quit (y/n) ? n
Do you want to quit (y/n) ? y
[sysadmin@localhost bin]$

Tulis komentar anda... Conversion Conversion Emoticon Emoticon

Thanks for your comment