[英]Error checking in script bash programming
我想知道我是否在進行正確的錯誤檢查? 基本上,如果文件復制失敗,則會彈出錯誤消息,然后如果發送文件不成功 go,則會彈出錯誤消息,刪除已創建的臨時文件。
file=$(mktemp /tmp/fileXXX)
rm_tmpfile () { rm -f $file; }
rm_tmpfilepod () { kubectl -n exec $z_pod -- rm $file }
z_pod=`kubectl -n get pod`
if (( kubectl -n cp $file $z_pod:/tmp/ )); then
echo
echo "Error: Copying the file to pod failed "
rm_tmpfilepod;
exit
fi
if (( kubectl -n exec $z_pod -- bash -c "/usr/bin/(doesnt matter)console-producer --bootstrap-server .tunnel.cluster.local:xxxx --topic < $file" )); then
echo
echo "Error: Sending file to a server failed"
rm_tmpfilepod;
exit 3
fi
rm_tmpfilepod
rm_tmpfile
我會做:
file=$(mktemp /tmp/fileXXX)
# Autocleanup with trap EXIT
trap_exit() {
rm -v "$file"
kubectl -n exec "$z_pod" -- rm -v "$file"
}
trap trap_exit EXIT
error() {
# error messages go to stderr, hence the name
echo "Error: $*" >&2
# exit with nonzero exit status
exit 1
}
# Check your script with shellcheck.
z_pod=$(kubectl -n get pod)
# (( )) is an __arithmetic__ expression. Has nothing to do with error checking.
# To check exit status of a command, just execute the command.
# Quotes! Check your script with shellcheck.
if ! kubectl -n cp "$file" "$z_pod":/tmp/; then
error "Copying the file to pod failed"
fi
cmd=(
kubectl -n exec "$z_pod" --
# Redirect first argument, command from second argument.
bash -c '"${@:2}" < "$1"' _
# Properly quote arguments.
"$file"
"/usr/bin/(doesnt matter)console-producer"
--bootstrap-server .tunnel.cluster.local:xxxx
--topic
)
if ! "${cmd[@]}"; then
error "Sending file to a server failed"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.