cmd1 && cmd2 如果命令cmd1 的result status 0,则执行cmd2,否则不执行cmd2命令。
cmd1 || cmd2 如果命令cmd1 的result status 1,则执行cmd2, 否则不执行cmd2命令。
可以用于异常出错处理:
i.e: 运行cmd1命令,如果cmd1运行出错,则输出一条提示信息。
解释:如果命令adb -s "device" logcat 执行出错, 则给用户提示"device not found."
i.e:
如下命令:
第一次执行该命令,由于当前命令下没有file1 file,执行[[ -e file1 ]] 命令的result status 为1 ; 不会执行命令echo "file1 file exits", 而对于touch file1 命令,由于之前的操作([[ -e file1 ]] && echo "file1 file exits.")的 result status 为1,因此,则执行touch file1
但运行第二次该命令时,[[ -e file1 ]] 命令返回0, 则执行echo "file1 file exits" ,而不执行touch file1命令。
cmd1 || cmd2 如果命令cmd1 的result status 1,则执行cmd2, 否则不执行cmd2命令。
可以用于异常出错处理:
i.e: 运行cmd1命令,如果cmd1运行出错,则输出一条提示信息。
adb -s "device" logcat || { echo "device not found"; exit 1; }解释:如果命令adb -s "device" logcat 执行出错, 则给用户提示"device not found."
i.e:
如下命令:
[[ -e file1 ]] && echo "file1 file exits." || touch file1第一次执行该命令,由于当前命令下没有file1 file,执行[[ -e file1 ]] 命令的result status 为1 ; 不会执行命令echo "file1 file exits", 而对于touch file1 命令,由于之前的操作([[ -e file1 ]] && echo "file1 file exits.")的 result status 为1,因此,则执行touch file1
但运行第二次该命令时,[[ -e file1 ]] 命令返回0, 则执行echo "file1 file exits" ,而不执行touch file1命令。
命令行条件执行与异常处理
本文详细介绍了在命令行中使用 && 和 || 运算符进行条件执行的方法,并通过实例展示了如何利用这些运算符进行异常错误处理。通过具体代码示例,读者可以学会在不同场景下灵活运用命令行条件执行技巧。
3505

被折叠的 条评论
为什么被折叠?



