functions-as-subshells.sh 858 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. # https://cuddly-octo-palm-tree.com/posts/2021-10-31-better-bash-functions/
  2. f() (
  3. # code
  4. var1=${1:-"default"}
  5. if [ "${var1}" == "default" ]; then
  6. #echo errors and warning messages to stderr 1>&2
  7. return 1 # error, outut undefined
  8. fi
  9. echo "StirngValueOnSTDOUT"
  10. return 0 # success, output defined
  11. )
  12. return=`f` && echo SUCCESS return value is $return || echo FAILURE no return
  13. echo
  14. return=`f FOO` && echo SUCCESS return value is $return || echo FAILURE no return
  15. echo
  16. if retval=f; then
  17. echo f with no argument succeeded
  18. else
  19. echo f with no argument failed
  20. fi
  21. if retval=`f BAR`; then
  22. echo f with an argument succeeded and retval is $retval
  23. else
  24. echo f with an argument failed
  25. fi
  26. if f BAR; then
  27. echo f with an argument succeeded, ignoring retval
  28. else
  29. echo f with an argument failed
  30. fi