mindthump

Bash best practices

Jul 19th, 2020 (edited)
1,427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.56 KB | None | 0 0
  1. # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
  2. set -Eeuxo pipefail
  3.  
  4. Best practices from Google:
  5.  
  6. # --- Process file line-by-line (don't pipe to 'while', use process substitution)
  7. last_line='NULL'
  8. while read line; do
  9.   if [[ -n "${line}" ]]; then
  10.     last_line="${line}"
  11.   fi
  12. done < <(your_command)
  13. # This will output the last non-empty line from your_command
  14. echo "${last_line}"
  15.  
  16. ## ... OR ...
  17.  
  18. last_line='NULL'
  19. readarray -t lines < <(your_command)
  20. for line in "${lines[@]}"; do
  21.   if [[ -n "${line}" ]]; then
  22.     last_line="${line}"
  23.   fi
  24. done
  25. echo "${last_line}"
  26. # This will output the last non-empty line from your_command
  27. echo "${last_line}"
  28.  
  29. # --- Testing strings
  30. # Do this:
  31. if [[ "${my_var}" == "some_string" ]]; then
  32.   do_something
  33. fi
  34.  
  35. # -z (string length is zero) and -n (string length is not zero) are
  36. # preferred over testing for an empty string
  37. if [[ -z "${my_var}" ]]; then
  38.   do_something
  39. fi
  40.  
  41. # This is OK (ensure quotes on the empty side), but not preferred:
  42. if [[ "${my_var}" == "" ]]; then
  43.   do_something
  44. fi
  45.  
  46. # --- Arrays
  47.  
  48. # An array is assigned using parentheses, and can be appended to
  49. # with +=( … ).
  50. declare -a flags
  51. flags=(--foo --bar='baz')
  52. flags+=(--greeting="Hello ${name}")
  53. mybinary "${flags[@]}"
  54.  
  55. # --- Check return status
  56. if ! mv "${file_list[@]}" "${dest_dir}/"; then
  57.   echo "Unable to move ${file_list[*]} to ${dest_dir}" >&2
  58.   exit 1
  59. fi
  60.  
  61. ## ... or ...
  62.  
  63. mv "${file_list[@]}" "${dest_dir}/"
  64. if (( $? != 0 )); then
  65.   echo "Unable to move ${file_list[*]} to ${dest_dir}" >&2
  66.   exit 1
  67. fi
Add Comment
Please, Sign In to add comment