简体   繁体   English

如何在bash脚本中将函数的返回值作为数组的索引传递?

[英]How to pass a return value of a function as an index of an array in bash script?

This is my program "try.sh": 这是我的程序“ 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”,则会出现此错误:

./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" 我想将函数is_odd()的返回值作为索引传递给名为“ type”的数组

Please tell me how can I make it work. 请告诉我如何使它工作。 Thanks. 谢谢。

Rather than having is_odd return its result as its status-code, I think it's better to print its result: 与其让is_odd返回其结果作为状态码,不如打印其结果:

is_odd()
{
    expr $1 % 2
}

Then you can use command-substitution ( `...` or $(...) ) to get the result: 然后,您可以使用命令替换( `...`$(...) )获得结果:

echo -e $in " is an " ${type[$(is_odd $in)]} " number."

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: 坦白地说,在这种特定情况下,我可能会放弃该函数并直接使用算术表达式,并且可能会为了提高可读性而对引号进行一些调整:

echo -e "$in is an ${type[in % 2]} number."

(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 without expr or ((...)) or whatnot.) (请注意,双引号"..."不要阻止参数替换${...}只有单引号'...'和反斜杠\\做到这一点。此外,帽尖jordanm用于指出数组索引被自动处理的算术表达式,即使没有expr((...))或诸如此类的东西。)

That said, if you really want to return 1 for "odd" and 0 for "even", then firstly, you should rename your function to is_even (since in Bash, 0 means "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. 也就是说,如果你真的想返回1为“奇”和0为“偶”,那么首先,你应该重命名功能is_even (因为Bash中, 0表示“成功”或“真”和非零值意味着“错误”或“假”),其次,您可以使用后续命令打印其返回值,然后使用命令替换。 Either of these should work: 这些都应该起作用:

echo -e "$in is an ${type[$(is_even $in ; echo $?)]} number."

echo -e "$in is an ${type[$(is_even $in && echo 0 || echo 1)]} number."

(By the way, I've also changed a to an in all of the above examples: in English it's "an odd number", "an even number".) (顺便说一句,我也改变了aan在上述所有例子:在英语中是“奇数”,“偶数”。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM