如何在此 bash 脚本中获取更好的错误消息?

如何在此 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"

我一直在尝试,但没用。:(

答案1

对于前者:

# 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 等。

你应该探索高级 Bash 脚本指南了解有关编写 shell 脚本的更多信息。 UNIX 编程环境的 shell 编程章节没有涵盖bash原始 Bourne shell 的扩展,但对于学习 shell 脚本的“禅意”仍然有用。

相关内容