1.判断命令是否存在
1.1 优雅方法1
首先,检查命令是否有效的惯用方法直接在if语句中。
if command; then echo notify user OK >&2else echo notify user FAIL >&2 return -1fi
(良好做法:使用>&2将消息发送给stderr。)
1.2 优雅方法2
将通用逻辑转移到共享函数中。
check() { local command=("$@") if "${command[@]}"; then echo notify user OK >&2 else echo notify user FAIL >&2 exit 1 fi}check command1check command2check command3
1.3 优雅方法3
installed () { command -v "$1" >/dev/null 2>&1}if installed <command1>then <command1> xxelse <command1> xxx fi
2.返回错误退出
2.1 || exit退出
command1 || exitcommand2 || exitcommand3 || exit
2.2 使用-e
$ bash -e xx.sh#!/bin/bash -e xx.shcommand1command2command3
Comments