eeval 724 B

12345678910111213141516171819202122232425262728
  1. #!/usr/bin/env bash
  2. # echo a command and eval it.
  3. # Can also print the command to a file.
  4. set -e
  5. a=
  6. while getopts a OPT; do
  7. case "$OPT" in
  8. a)
  9. # Append to file instead of overwriting.
  10. a=-a
  11. ;;
  12. ?)
  13. exit 2
  14. ;;
  15. esac
  16. done
  17. shift "$(($OPTIND - 1))"
  18. cmd="$1"
  19. outfile="${2:-/dev/null}"
  20. mkdir -p "$(dirname "$outfile")"
  21. echo "$cmd" | tee $a "$outfile"
  22. # PIPESTATUS so that cmd="main_cmd | post_process" will return the status of cmd.
  23. # Not POSIX.
  24. # https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another
  25. # https://stackoverflow.com/questions/1221833/pipe-output-and-capture-exit-status-in-bash
  26. eval "${cmd}; cmd_exit=\${PIPESTATUS[0]}"
  27. exit "$cmd_exit"