1、判断语法
if [ command1 ]; then
do_command1
elif [ command2 ]; then
do_command2
else
do_command3
fi
#上条命令运行结果判断
command
if [ $? -eq 0 ]; then
echo "command execution success"
elif [ $? -eq 1 ]; then
echo "command execution fail"
fi
case $para in
0)do_command1;;
1)do_command2;;
[abcd]do_command3;;
string1)do_command4;;
*string2*)do_command5;;
2|string3)do_command6;;
*)do_command7;;
esac
[ command ] && do_command
[ command ] || do_command
#command 结果为真执行{}中的命令
[ command ] && {
do_command
...
}
#command 结果为非真执行{}中的命令
[ command ] || {
do_command
...
}
#command1为非真 command2 command3结果为真执行{}中的命令
[ command1 ] || [ command2 ] && [ command3 ] && {
do_command
...
}
#判断、行号输出以及函数参数传递
#!/bin/bash
func() {
[ $1 = 0 ] && [ $2 != 0 ] && [ $3 = "aaa" ] && {
eval $4=true
echo "lineno is $LINENO"
} || eval $4=false
}
func 0 0 aaa ret
echo $ret
func 0 1 aaa ret
echo $ret
2、循环语法
until false
do
do_command
done
while true
do
do_command
done
for ((;;))
do
do_command
done
for idx in 1 2 3 4
do
do_command
done
while [ command ]
do
do_command1
[ do_command2 ] && break;
done
#读取文件1
while read line
do
#通过长度判断是否为空行
if [ ${#line} -gt 1 ]; then
echo $line
fi
done < filename
#读取文件2
cat filename | while read line
do
#通过长度判断是否为空行
if [ ${#line} -gt 1 ]; then
echo $line
fi
done
3、运算语法
#使用$(expr )
result=$(expr $num1 + $num2 - $num3 * $num4 / $num5)
#使用$(( ))
result=$(($num1 + $num2 - $num3 * $num4 / $num5))
4、调试
DEBUG=1
print_msg() {
if [ $DEBUG -eq 1 ]; then
echo > /dev/console "debug==>$@"
fi
}
printf "%s %d\n" DEBUG $DEBUG
print_msg "line:$LINENO DEBUG=$DEBUG"