Is This Bash Example Correct?
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
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
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
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
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