如何在这个bash脚本中获得更好的错误消息?

我试图在运行命令时捕获任何错误,以便编写日志文件/报告

我试过这段代码:

function valid (){ if [ $? -eq 0 ]; then echo "$var1" ": status : OK" else echo "$var1" ": status : ERROR" fi } function save(){ sed -i "/:@/c connection.url=jdbc:oracle:thin:@$ip:1521:$dataBase" $search var1="adding database ip" valid $var1 sed -i "/connection.username/c connection.username=$name" #$search var1="addning database SID" valid $var1 } save 

输出如下:

 adding database ip : status : OK sed: no input file 

但我希望它看起来像这样:

 adding database ip : status : OK sed: no input file : status : ERROR" 

或这个:

 adding database ip : status : OK addning database SID : status : ERROR" 

我一直在努力,但它不适合我。 🙁

对于前者:

 # run sed, capture any output var1="$(sed -i "/connection.username/c connection.username=$name" $search)" 

对于后者:

 # run sed, discard all output but keep exit status sed -i "/connection.username/c connection.username=$name" $search >/dev/null 2>&1 

也就是说, valid()是……奇怪,至少可以说。 我会把它写成

 # valid label [status] # check status ($? if not provided) and log success/failure function valid { if [[ ${2-$?} == 0 ]]; then echo "$1 : status : OK" else echo "$1 : status : ERROR" fi } 

实际上,我会从一开始就做一些不同的事情:

 # log label command [arguments...] # run command, output success/failure to stderr. If label is empty, use the # command name: 'log "" echo hi' uses 'echo' as the label. # log entries look like # label1 : status : OK # label2 : status : ERROR # Error output from foo: # Baz is broken; fix and try again. log() { # save off label local label="${1:-$2}" shift # this removes $1 and shifts $2... to $1... so "$@" works later # run command, capture output # $(command) runs 'command' and substitutes its output # "$@" preserves quoting; $* would turn argument "foo bar" into two # arguments foo bar err="$("$@")" if [[ $? == 0 ]]; then status=OK else status=ERROR fi echo "$label : status : $status" >&2 # standard error if [[ $status == ERROR ]]; then # log output from command, indented for clarity echo "Error output from $2:" echo "$err" | sed 's/^/ /' >&2 fi } save() { # this sed command is pedantically correct; if GNU sed lets you # do single-line 'c' commands as in the original, then go for it. # The backslash-return after the label argument is just for clarity; # 'log "foo" bar' works just as well. log "adding database ip" \ sed -i "/:@/c\\ connection.url=jdbc:oracle:thin:@$ip:1521:$dataBase\\ ." "$search" # using the original (GNU?) sed syntax log "adding database SID" \ sed -i "/connection.username/c connection.username=$name" "$search" } save 

我还会在真实程序中包含时间戳和程序ID等。

您可能应该浏览Advanced Bash Scripting Guide以了解有关编写shell脚本的更多信息。 UNIX编程环境的shell编程章节不涉及原始Bourne shell的bash扩展,但仍然有助于学习shell脚本的“禅”。