Bash functions normally "return" values by printing them to standard output, where the caller can capture them using
`func args ...`
or
$(func args ...)
This makes functions work like external commands.
The return
statement, on the other hand, sets the value of $?
. Normally that's going to be set to 0 for success, 1 for failure, or some other value for a specified kind of failure. Think of it as a status code, not a general value. It's likely that this will only support values from 0 to 255.
Try this instead:
#!/bin/sh
div3() {
expr $1 % 3 = 0 # prints "0" or "1"
}
d=$(div3 1)
echo $d
Note that I've also changed the shebang line from #!/usr/bin/env sh
to #!/bin/sh
. The #!/usr/bin/env
trick is often used when invoking an interpreter (such as perl
) that you want to locate via $PATH
. But in this case, sh
will always be in /bin/sh
(the system would break in various ways if it weren't). The only reason to write #!/usr/bin/env sh
would be if you wanted to use whatever sh
command happens to appear first in your $PATH
rather than the standard one. Even in that case you're probably better of specifying the path to sh
directly.