Shell Script While Loop Examples

Can you provide me a while loop control flow statement shell script syntax and example that allows code to be executed repeatedly based on a given boolean condition?

Each while loop consists of a set of commands and a condition. The general syntax as follows for bash while loop:

Advertisement

while [ condition ]
do
	command1
	command2
	commandN
done
  1. The condition is evaluated, and if the condition is true, the command1,2…N is executed.
  2. This repeats until the condition becomes false.
  3. The condition can be integer ($i < 5), file test ( -e /tmp/lock ) or string ( $ans != "" )

ksh while loop syntax:

while [[ condition ]] ; do
	command1
	command1
	commandN
done

csh while loop syntax:

     while ( condition )
         commands
     end

BASH while Loop Example

#!/bin/bash
c=1
while [ $c -le 5 ]
do
	echo "Welcone $c times"
	(( c++ ))
done

KSH while loop Example

#!/bin/ksh
c=1
while [[ $c -le 5 ]]; do
	echo "Welcome $c times"
	(( c++ ))
done

CSH while loop Example

#!/bin/csh
c=1
while ( $c <= 5 )
	echo "Welcome $c times"
	@ c = $c + 1
end

Another example:

#!/bin/csh
set yname="foo"
while ( $yname != "" )
	echo -n "Enter your name : "
	set yname = $<
	if ( $yname != "" ) then
		echo "Hi, $yname"
	endif
end

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

27 comments… add one
  • Paulo M.S Jul 4, 2015 @ 0:43

    Muito bom, me ajudou muito mesmo!!! valeu

  • Simrandeep Jul 17, 2016 @ 7:12

    How to write a script in c shell which write all numbers from input number down to 1 using a loop

  • manhoud Sep 7, 2016 @ 22:25

    #!/bin/bash
    LINKS_FILE="ips"
    for link in `cat "$LINKS_FILE"`
    do
    res=$(curl -m 1 "http://${link}" --user admin:admin )
    if echo $res | grep -i "stats"; then
    echo "https://"$link >> logs
    fi
    done

    how i read password from file

  • Sarath Mar 26, 2017 @ 13:02

    a=1
    b=$1
    until [ $a -ge $b ]
    do
    echo “*”
    echo “**”
    echo “***”
    echo “****”
    echo “*****”
    echo “******”
    a=$((a+2))
    done

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.