目录

循环的形式

不仅可以用数字,还可以用字母

For循环

echo {1..50} 能够生成一个从1~50的数字列表。 echo {a..z} 或 {A..Z} 或 {a..h} 可以生 成字母列表。同样,我们可以将这些方法结合起来对数据进行拼接(concatenate) 。下面的 代码中,变量 i 在每次迭代的过程里都会保存一个字符,范围从 a ~ z :

for i in {a..z}; do actions; done;

#for 循环也可以采用C语言中 for 循环的格式。例如:
for((i=0;i<10;i++))
{
  commands; #使用变量$i
}

while循环

while condition
do
  commands;
done

#用 true 作为循环条件能够产生无限循环。

until循环

在Bash中还可以使用一个特殊的循环 until 。它会一直执行循环,直到给定的条件为真。

例如:

x=0;
until [ $x -eq 9 ]; #条件是[$x -eq 9 ]
do
  let x++; echo $x;
done

#输出结果

[root@centos76 ~]# sh 2.txt
1
2
3
4
5
6
7
8
9

if条件

if 条件

if condition;
then
  commands;
fi

else if 和 else

if condition;
then
  commands;
else if condition; then
  commands;
else
  commands;
fi

if条件简化写法



 [ condition ] && action; #  如果 condition 为真,则执行 action ;
 [ condition ] || action; #  如果 condition 为假,则执行 action 。



判断条件的常见应用

文件系统

文件系统相关测试,可以使用不同的条件标志测试不同的文件系统相关的属性。

  1. 文件、目录是否存在
  2. 文件是否具有可执行、读写权限
  3. 是否为符号链接

使用方法如下:


fpath="/etc/passwd"
if [ -e $fpath ]; then
  echo File exists;
else
  echo Does not exist;
fi

字符串比较

使用字符串比较时,最好用双中括号,因为有时候采用单个中括号会产生错误,所以最 好避开它们。

可以用下面的方法检查两个字符串,看看它们是否相同。

str1="Not empty "
str2=""
if [[ -n $str1 ]] && [[ -z $str2 ]];
then
  echo str1 is nonempty and str2 is empty string.
fi
#输出如下:
str1 is nonempty and str2 is empty string.

test命令

test 命令可以用来执行条件检测。用 test 可以避免使用过多的括号。之前讲过的 [] 中的测试条件同样可以用于 test 命令。 例如:

if [ $var -eq 0 ]; then echo "True"; fi
也可以写成:
if test $var -eq 0 ; then echo "True"; fi