b"elif [ $1 -lt $2 ];thenecho "a < b"elseecho ..._go写linux脚本">
赞
踩
流程控制
本文章原创首发于公众号:编程三分钟[]()
这一次我们的主题是shell脚本中的流程控制,gif动图所见即所得,语法如下。
if else
#!/bin/bash
if [ $1 == $2 ];then
echo "a == b"
elif [ $1 -gt $2 ];then
echo "a > b"
elif [ $1 -lt $2 ];then
echo "a < b"
else
echo "error"
fi
[]()
for 循环
#!/bin/bash
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
[]()
while 循环
#!/bin/bash
i=0
while [[ $i<3 ]]
do
echo $i
let "i++"
done
输出
while的判断条件可以从键盘输入,成为交互式的脚本
#!/bin/bash
echo 'press exit'
while read num
do
echo "you input is $num"
done
ps: until循环与while循环相反,until直到判断条件为真才停止,语法同while完全一样就不多介绍了。
[]()
死循环
while true
do
command
done
或者
for (( ; ; ))
do
command
done
死循环,使用Ctrl+C退出。
[]()
跳出循环
就是continue和break
case
#!/bin/bash
case $1 in
1) echo 'You have chosen 1'
;;
2) echo 'You have chosen 2'
;;
*) echo 'You did not enter a number between 1 and 2'
;;
esac
同编程语言中的switch一样,只有语法略微不同 ,esac为case的结束符。
每个模式,用右括号结束),如果没有任何匹配的就用*),每个模式用;;两个分号连一起结束。
case 值 in
模式1)
command1
command2
...
commandN
;;
模式2)
command1
command2
...
commandN
;;
esac
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。