shell常用语法

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"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值