2020-04-10 linux循环

时间:2020-04-10
本文章向大家介绍2020-04-10 linux循环,主要包括2020-04-10 linux循环使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.for循环

#!/bin/bash
for i in 1 2 3 4
do 
    echo $i
done
$ chmod +x for.sh
$ ./for.sh
1
2
3
4

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

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

2.while循环

#!/bin/bash
n=1
while [ $n -le 4 ]
do
    echo $n
    ((n++))
done
$ chmod +x while.sh
$ ./while.sh
1
2
3
4

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

3.循环嵌套

#!/bin/bash
n=1
while [ $n -lt 4 ]
do
    for l in {a..c}
    do
        echo $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
while true
do
    echo -n "Still running at "
    date
    sleep 1
done

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" ]; then
    echo ok1
fi
if [[ $ans = *[[:digit:]]* ]]; then
    echo ok2
fi
if [[ "$ans" =~ ^[0-9]+$ ]]; then
    echo ok3
fi

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

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

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

再看一个例子:

#!/bin/bash

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

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

7.其他用法

#!/bin/bash

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

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

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