This is my program “try.sh”:
in=$*
type=(even odd)
echo -e $in " is a " ${type[is_odd $in]} " number."
is_odd()
{
return `expr $1 % 2`
}
But if I execute “./try.sh” it gives me this error:
./try.sh: line 3: is_odd 2: syntax error in expression (error token is "2")
I want the return value of the function is_odd() to be passed as an index to the array named “type”
Please tell me how can I make it work. Thanks.
Rather than having
is_oddreturn its result as its status-code, I think it’s better to print its result:Then you can use command-substitution (
`...`or$(...)) to get the result:Though to be honest, in this specific case I’d probably just get rid of the function and use the arithmetic expression directly — and probably adjust the quoting a bit for readability:
(Note that double quotes
"..."do not prevent parameter substitution${...}. Only single-quotes'...'and backslashes\do that. Also, hat-tip to jordanm for pointing out that array indices are automatically treated as arithmetic expressions, even withoutexpror((...))or whatnot.)That said, if you really want to return
1for “odd” and0for “even”, then firstly, you should rename your function tois_even(since in Bash,0means “successful” or “true” and nonzero values mean “error” or “false”), and secondly, you can use a follow-on command to print its return value, and then use command-substitution. Either of these should work:(By the way, I’ve also changed
atoanin all of the above examples: in English it’s “an odd number”, “an even number”.)