简体   繁体   中英

Error checking in script bash programming

I was wondering if im doing correct error checking? basically if the copying of file fails then errors message pops up then if sending file doesnt go well then error pops up remove tempfiles that were created.

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

I would do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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