Is This Bash Example Correct?

0
8
Asked By CuriousCoder42 On

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

Answered By BashEnthusiast7 On

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.

Answered By ScriptGuru88 On

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!

Answered By BashBot3000 On

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!

Answered By CodeTraveler99 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.