Bash

bash 腳本在失敗時列印標準錯誤

  • February 27, 2022

如果一切正常,我正在嘗試使 bash 腳本靜默,但如果由於某種原因崩潰,則列印出所有 stderr 和調試資訊。以下是我到目前為止所擁有的。

#!/usr/bin/bash

set -e

rm -f /tmp/err
trap "sleep 1 && cat /tmp/err" ERR

l() {
   ts >> /tmp/err
}

echo "About to download stuff:" > >(l)
# curl blah blah 2> >(l)

# something goes wrong in the script
invalid_cmd

只有當我有我不喜歡的“睡眠 1”時,它才能正常工作。

不睡覺:

❯ ./demo2.sh    
./demo2.sh: line 18: invalid_cmd: command not found

與睡眠:

❯ ./demo2.sh
./demo2.sh: line 18: invalid_cmd: command not found
Feb 25 15:20:44 About to download stuff:

我認為這是因為程序替換在後台執行並且可能無法完成。我也不想盲目地wait處理所有後台任務。有沒有更好的方法來解決這個問題?

經過更多的黑客攻擊,找到了以下解決方案。

#!/usr/bin/bash

set -e

make_temp_fds() {
   local tfile=$(mktemp)
   exec {fdw}>$tfile {fdr1}<$tfile {fdr2}<$tfile
   rm $tfile
}
   
setup_err_fd() {
   make_temp_fds
   local raw_fdw=$fdw raw_fdr=$fdr1

   make_temp_fds
   local ts_fdw=$fdw ts_fdr=$fdr1

   ts <&$raw_fdr >&$ts_fdw &
   tspid=$!
   trap "wait $tspid && cat <&$ts_fdr" ERR

   err_fd=$raw_fdw
}

# Calling this function, will give you $err_fd
# Anything written to $err_fd will be saved in a temporary file with timestamps 
# and printed out if the script fails with an error. 
# Will be lost if script exits successfully
setup_err_fd

echo "all setup"

echo "debug line 1" >&$err_fd

echo "debug line 2" >&$err_fd

not_ok
#echo "ok"

echo "bye"

不幸的是,它涉及兩個臨時文件。我試圖讓其中一個成為管道,但無法正常工作。隨意改進

引用自:https://unix.stackexchange.com/questions/692148