结构化命令包含:if,while,for三类;
1>if
基本用法:
if command
then
commands
fi
如:
if [ 1 > 2 ];then
echo "hello"
fi
if用fi表示结束。
一些其他的格式,如果用过其他语言的话,都会存在,if...else..., if ....else if(...)...其他格式。
shell也不例外:
if...else...
if command
then
commands
else
commands
fi
if...elif...
if command
then
commands
elif command
then
commands
fi
if的嵌套格式,if会与离它最近的fi进行匹配。if后面跟着的命令可以有多种形式。
2>for
基本形式:
for var in list
do
commands
done
有很多种指定值列表的方法。
(1)直接指定(只要每个值之间用空格分割,就可以遍历)
如:
for var in 1 2 3 4 5 6 7
do
echo "$var"
done
(2)从变量中读取
如:
values="0 1 2 3 4 5"
for var in $values
do
echo "$var"
done
还有一种遍历值的方式,使用IFS指定字符,然后遍历,丛书中看到的,未在实际项目中使用过,不过挺方便的。
如:
IFS=',’(IFS:内部字段分割符)
values="1,2,3,4,5"
for var in $values
do
echo "$var"
done
还有一种C语言分割的for循环,不过感觉别扭,从未使用过,保不准哪天会用到。
for (( a = 1; a <= 3; a++)
do
done
大体类似该格式。
3>while
基本格式:
while test command
do
commands
done
只要测试条件成立,while循环就会一直执行下去。
在工作中,我需要读取文件,我比较常用这种方式读取:
while read line
do
echo "$line"
done < "$filename"
最后,就是break及continue;
break:跳出全部循环
continue:只跳过本次循环。
以上就是我所了解的结构化命令。