当前位置:首页 > 操作系统 > Linux

2020-04-10 linux循环

1.for循环

#!/bin/bash
for i in1234doecho $i
done
$ chmod +x for.sh
$ ./for.sh1234

如果要循环的内容是字母表里的连续字母或连续数字

#!/bin/bash
for x in {a..d}
doecho $x
done
$ ./for.sh
a
b
c
d

2.while循环

#!/bin/bash
n=1while [ $n -le 4 ]
doecho $n
    ((n++))
done
$ chmod +x while.sh
$ ./while.sh1234

循环次数比较少的情况下,for 循环与 while 循环效果差不多,但如果循环次数比较多,比如 10 万次,那么 while 循环的优势就体现出来了。

3.循环嵌套

#!/bin/bash
n=1while [ $n -lt 4 ]
dofor l in {a..c}
    doecho $n$l
    done
    ((n++))
done
$ chmod +x while_with_for.sh
$ ./while_with_for.sh
1a
1b
1c
2a
2b
2c
3a
3b
3c

4.死循环

#!/bin/bash
whiletruedoecho -n "Still running at "datesleep1done

Ctrl C 终止死循环

5.按行读取文本内容

#!/bin/bash
echo -n "Enter file> "
read file
n=0
while read line; 
do ((n++)) echo"$n: $line"done < $file

在这里,使用 read 命令将文本文件的内容读取存入 file 变量,然后再使用重定向(上述脚本最后一行)将 file 内容依次传入 while 循环处理再打印出来。

$ chmod +x file.sh
$ ./file.sh
Enter file> test.txt #test.txt为同一目录下的文本文件
1:line1
2:I am line2:
3:line3

6.变量检查

#!/bin/bash

echo -n "How many times should I say hello? "
read ans
if [ "$ans" -eq "$ans" ]; thenecho ok1
fiif [[ $ans = *[[:digit:]]* ]]; thenecho ok2
fiif [[ "$ans" =~ ^[0-9]+$ ]]; thenecho ok3
fi

第一种方法看起来似乎是个废话,但实际上,-eq 只能用于数值间判断,如果是字符串则判断不通过,所以这就保证了 ans 是个数值型变量。

第二种方法是直接使用 Shell 的通配符对变量进行判断。

第三种方法就更直接了,使用正则表达式对变量进行判断。

再看一个例子:

#!/bin/bash

echo -n "How many times should I say hello? "
read ans
if [ "$ans" -eq "$ans" ]; then
  n=1while [ $n -le $ans ]
  doecho hello
    ((n++))
  donefi

在这个脚本里,将要循环的次数传入到 ans 变量,然后脚本就具体打印几次 hello 。为了保证我们传入的内容是数字,我们使用了 if [ "$ans" -eq "$ans" ] 语句来判断。如果我们传入的不是数字,则不会进入 while 循环。

7.其他用法

#!/bin/bash

$ echo -n "hostname"
$ echo `hostname`
$ chomd +x other_usage.sh
$ ./other_usage.shhostname: ubuntu

注意:echo `hostname` 执行系统命令时需要用``而不是‘’

 

原文:https://www.cnblogs.com/cxl-blog/p/12672496.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!