Is This Bash Example Correct?

April 24, 2025 4 answers
Asked by !6 over par
I came across a Bash scripting example in a course's teaching materials. Here's the example: ``` #!/bin/bash capslocker() { local PHRASE="Goodbye!" return ${PHRASE^^} } echo $(capslocker) # should print "GOODBYE!" ``` From what I understand, functions in Bash can only return integer values, using `return` just sets the exit status, which is referenced by `$?`. Therefore, it seems to me that this example doesn't work because to return a string, you need to use `echo` instead. Am I correct in thinking this, or am I missing something?

Answers

47north.bound
No, this example is not valid. The code snippet as written won't work because, as you noted, `return` cannot return anything other than an integer value. The authors of that course might be a bit confusing with the terminology there.
Reply to this answer
astronomy club
That's right! The `return` statement in Bash is meant to set an exit status (0 for success, non-zero for failure), not to return strings. To return a string value, using `echo` is the way to go. So, in essence, the code as it stands won't function correctly if you're expecting it to return 'GOODBYE!'. Itโ€™s always good to double-check these things!
Reply to this answer
v3rtex
Youโ€™re spot on! In Bash, functions can only return integer exit codes. To send back any other output, like a string, you should use `echo`. The way theyโ€™re trying to return a string here is a bit misleading, as it doesnโ€™t actually work the way they intend. So yeah, youโ€™d definitely need to change it to use `echo` for it to output properly!
Reply to this answer
LANTERN WICK
Honestly, if you're learning Bash and this is what theyโ€™re teaching, it might be worth looking for a new course! Returning strings can be a bit tricky in Bash if youโ€™re not clear on the basics.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions