我試圖random_fail.sh通過在第二個腳本catch_error.sh(
#!/usr/bin/env bash
# random_fail.sh
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
exit 1
fi
echo "Everything went according to plan"
#!/usr/bin/env bash
# catch_error.sh
count=0 # The number of times before failing
error=0 # assuming everything initially ran fine
while [ "$error" != 1 ]; do
# running till non-zero exit
# writing the error code from the radom_fail script into /tmp/error
bash ./random_fail.sh 1>/tmp/msg 2>/tmp/error
# reading from the file, assuming 0 written inside most of the times
error="$(cat /tmp/error)"
echo "$error"
# updating the count
count=$((count 1))
done
echo "random_fail.sh failed!: $(cat /tmp/msg)"
echo "Error code: $(cat /tmp/error)"
echo "Ran ${count} times, before failing"
我期待 catch_error.sh 將從 /tmp/error 讀取并在 random_fail.sh 的特定運行以 1 退出時退出回圈。
相反,catch 腳本似乎永遠在運行。我認為這是因為錯誤代碼根本沒有被重定向到 /tmp/error 檔案。
請幫忙。
uj5u.com熱心網友回復:
您沒有以正確/通常的方式捕獲錯誤代碼。此外,當它已經包含 shebang 時,無需在執行前加上“bash”命令。最后,好奇你為什么不簡單地使用#!/bin/bash而不是#!/usr/bin/env bash。
您的第二個腳本應修改為如下所示:
#!/usr/bin/env bash
# catch_error.sh
count=0 # The number of times before failing
error=0 # assuming everything initially ran fine
while [ "$error" != 1 ]; do
# running till non-zero exit
# writing the error code from the radom_fail script into /tmp/error
./random_fail.sh 1>/tmp/msg 2>/tmp/error
error=$?
echo "$error"
# updating the count
count=$((count 1))
done
echo "random_fail.sh failed!: $(cat /tmp/msg)"
echo "Error code: ${error}"
echo "Ran ${count} times, before failing"
uj5u.com熱心網友回復:
[ "$error" != 1 ]如果向 stderr列印一個單獨的數字,則為真。只要不發生這種情況,您的腳本就會回圈。您可以改為測驗是否有任何內容寫入stderr。有幾種可能實作這一點:random_fail.sh1
printf '' >/tmp/error
while [[ ! -s /tmp/error ]]
或者
error=
while (( $#error == 0 ))
或者
error=
while [[ -z $error ]]
uj5u.com熱心網友回復:
/tmp/error將始終為空或包含“錯誤使用幻數”行。它永遠不會包含 0 或 1。如果你想知道腳本的退出值,直接查看即可:
if ./random_fail.sh 1>/tmp/msg 2>/tmp/error; then error=1; else error=0; fi
或者,您可以這樣做:
./random_fail.sh 1>/tmp/msg 2>/tmp/error
error=$?
但不要這樣做。做就是了:
while ./random_fail.sh; do ...; done
只要random_fail.sh(請閱讀https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/并停止使用.sh后綴命名您的腳本)回傳 0,就會進入回圈體。當它回傳非零時,回圈終止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/528972.html
標籤:重击壳
