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?
4 Answers
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.
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!
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!
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.
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String