linux基本操作---shell编程之 while循环

java中我们经常用到while循环,那么shell中也有while循环:

while简单循环

直接看demo:

demo1: 求1-10的和

[root@dev-02 software]# cat while1to10.sh 
#!/bin/bash
i=1
while [ $i -le 10 ]
do
    sum=$((sum+i))
    i=$((i+1))
done
echo $sum


[root@dev-02 software]# sh while1to10.sh 
55

问题:
开始的时候 老是报错,我们的写法是

报错:
[root@dev-02 software]# sh while1to10.sh 
while1to10.sh: line 3: while[1 -le 10]: command not found
while1to10.sh: line 4: syntax error near unexpected token `do'
while1to10.sh: line 4: `do'

脚本:
[root@dev-02 software]# cat while1to10.sh 
#!/bin/bash
i=1
while[$i -le 10]
do
    sum=$((sum+i))
    i=$((i+1))
done
echo $sum

之后修改
while的参数之间需要用空格隔开,问题解决,这个语法真6,无语了,苦笑。

while读取文件内容:

读取文件,遍历every line ,有next line ,就echo line

[root@dev-02 software]# cat readwhile.sh 
#!/bin/bash
while read -r line
do
    echo $line
done < /etc/passwd



[root@dev-02 software]# sh readwhile.sh 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
..
.

关于-r 我们看一下帮助文档,可以发现-r是不考虑转义字符。

-r Backslash does not act as an escape character. The backslash is considered to be part of the line. In par-
ticular, a backslash-newline pair may not be used as a line continuation.

你可能感兴趣的:(linux/shell基础)