Shell
语法
if-then 语句
- if [ 测试条件成立 ] 或 命令返回值是否为0
then 执行命令
fi 结束
if-then-else 语句
- if [ 测试条件成立 ]
then 执行命令
else 条件不成立时,执行相应命令
fi 结束
-if [ 测试条件成立 ]
then 执行命令
elif 条件成立
then 执行命令
else 条件不成立时,执行相应命令
fi 结束
- case 语句示例
#!/bin/bash
# case demo
case "$1" in
"start"|"START")
echo $0 start...
;;
"stop")
echo $0 stop...
;;
"restart"|"reload")
echo $0 restart...
;;
*)
echo "usage: $0 {start|stop|restart|reload}"
;;
$ ./1.sh start/stop/restart
for 循环语法
- for 参数 in 列表
do 执行的命令
done 封闭一个循环
例:
touch a.mp3 b.mp3 c.mp3
for filename in `ls *.mp3`
do
mv $filename $(basename $filename .mp3).mp4
done
-
使用反引号或 $() 方式执行命令,命令的结果当做列表处理
-
列表中包含多个变量,变量使用空格隔开
-
对文本处理,要使用文本查看命令取出文本内容
- 默认逐行处理,如果文本出现空格会当做多行处理
-
C语言风格的for 命令
for((变量初始化;循环判断条件;变量变化))
do
循环执行的命令
done
while 循环
- while [ test测试是否成立 ]
do
命令
done