給定以下人為的代碼:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
echo 'before'
mapfile -t tuples < <(exit 1)
# ^ what option do I need to enable so the error exit code from this is not ignored
echo 'after'
產生:
before
after
是否有一個 set 或 shopt 選項可以打開,這樣<(exit 1)會導致呼叫者繼承失敗,從而防止after被執行?比如在其他情況下做什么inherit_errexit和做什么。pipefail
uj5u.com熱心網友回復:
在bash4.4 或更高版本中,將設定行程替換$!,這意味著您可以等待該行程以獲取其退出狀態。
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
echo 'before'
mapfile -t tuples < <(exit 1)
wait $!
echo 'after'
mapfile本身(通常)不會具有非零狀態,因為它非常高興地閱讀程序替換產生的內容(如果有的話)。
uj5u.com熱心網友回復:
您可以使用命令的輸出分配一個變數。變數賦值會傳播來自命令替換的錯誤。
t=$(exit 1)
echo 'after'
mapfile -t tuples <<<"$t"
uj5u.com熱心網友回復:
如果你有 Bash 4.2 或更高版本,因為你已經設定了errexitand pipefail,你可以通過使用來避免這個問題:
...
shopt -s lastpipe
exit 1 | mapfile -t tuples
shopt -s lastpipe導致管道中的最后一個命令在當前 shell 中運行。看看如何shopt -s lastpipe影響 bash 腳本的行為?. 在這種情況下,這意味著可以稍后在代碼中訪問tuples讀取的值。mapfile
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467909.html
