I’m writing a divides-by-three function in Bash, and it won’t let me set a variable to a number.
fizzy.sh:
#!/usr/bin/env sh
div3() {
return `$1 % 3 -eq 0`
}
d=div3 1
echo $d
Example:
$ ./fizzy.sh
./fizzy.sh: line 7: 1: command not found
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Bash functions normally “return” values by printing them to standard output, where the caller can capture them using
or
This makes functions work like external commands.
The
returnstatement, 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:
Note that I’ve also changed the shebang line from
#!/usr/bin/env shto#!/bin/sh. The#!/usr/bin/envtrick is often used when invoking an interpreter (such asperl) that you want to locate via$PATH. But in this case,shwill always be in/bin/sh(the system would break in various ways if it weren’t). The only reason to write#!/usr/bin/env shwould be if you wanted to use whatevershcommand happens to appear first in your$PATHrather than the standard one. Even in that case you’re probably better of specifying the path toshdirectly.