util.sh 1018 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # shared shell functions
  2. info() {
  3. local msg="$@"
  4. local timestamp="$(date +%H:%M:%S)"
  5. say "===> ${timestamp} ${msg}" "green"
  6. }
  7. warn() {
  8. local msg="$@"
  9. local timestamp=$(date +%H:%M:%S)
  10. say "===> ${timestamp} WARN: ${msg}" "yellow" >&2
  11. }
  12. fail() {
  13. local msg="$@"
  14. say "ERROR: ${msg}" "red" >&2
  15. exit 1
  16. }
  17. # say prints the given message to STDOUT, using the optional color if
  18. # STDOUT is a terminal.
  19. #
  20. # usage:
  21. #
  22. # say "foo" - prints "foo"
  23. # say "bar" "red" - prints "bar" in red
  24. # say "baz" "green" - prints "baz" in green
  25. # say "qux" "red" | tee - prints "qux" with no colour
  26. #
  27. say() {
  28. local msg=$1
  29. local color=$2
  30. if [[ -n "${color}" ]] && [[ -t 1 ]]; then
  31. case "${color}" in
  32. red)
  33. echo -e "\033[1;31m${msg}\033[0m"
  34. ;;
  35. green)
  36. echo -e "\033[1;32m${msg}\033[0m"
  37. ;;
  38. yellow)
  39. echo -e "\033[1;33m${msg}\033[0m"
  40. ;;
  41. *)
  42. echo "${msg}"
  43. ;;
  44. esac
  45. else
  46. echo "${msg}"
  47. fi
  48. }