Shell Script While Loop Examples

来源:互联网 发布:知乎 华清远见骗局 编辑:程序博客网 时间:2024/06/12 01:27

by Vivek Gite on July 16, 2009 · 7 comments

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:

while [ condition ]docommand1command2commandNdone
  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 ]] ; docommand1command1commandNdone 

csh while loop syntax:

     while ( condition )         commands     end 

BASH while Loop Example

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

KSH while loop Example

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

CSH while loop Example

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

Another example:

#!/bin/cshset yname="foo"while ( $yname != "" )echo -n "Enter your name : "set yname = $<if ( $yname != "" ) thenecho "Hi, $yname"endifend

Featured Articles: