繁体   English   中英

脚本 bash 编程中的错误检查

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM