while statement

  1. A while loop is used to continuously execute a series of commands, usually to test a condition.
#!/bin/sh
n=1
while(( $n<=6 ))
do
    echo $n
    let "n++"
done

The Bash let command is used in use, which is used to execute one or more expressions. There is no need to add $ to indicate variables in variable calculation. For details, please refer to: Bash let command

#!/bin/bash
n=1
while [ $n -le 6 ]; 
do 
echo $n;
n=$((n + 1)); 
done

$ n=1
$ while [ $n -le 6 ]
> do echo $n
> n=`expr $n + 1`
> done

#运行脚本,输出:
1
2
3
4
5
6

2.While loop can be used to read keyboard information. In the following example, the input information is set to the variable text, press to end the loop.

#!/bin/bash
echo '按下 <CTRL-D> 退出'
while read text
do
    echo ${text}
done
# 运行脚本,输出类似下面:
按下 <CTRL-D> 退出
Hello world!
Hello world!

3. Use read to read data on standard input

#!/bin/bash
while read text
do
  echo ${text}
done < /home/username/test1

#输出:
Hello world!

Finally, the input redirection takes the contents of /home/username/test1 as the standard input of this script. The output of this script is the contents of the /test1 file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325446065&siteId=291194637