问题描述
我正在写bash中的一种划分,由三个功能,它不会让我一个变量设置为一个数字。
fizzy.sh:
#!的/ usr / bin中/ env的SHDIV3(){
返回`$ 1%3当量0`
}D = 1 DIV3
回声$ d个
例如:
$ ./fizzy.sh
./fizzy.sh:行7:1:命令未找到
Bash函数通常是回归他们打印到标准输出,其中主叫方可以通过捕捉它们的值
`FUNC ARGS ...`
或
$(FUNC ARGS ...)
这使得职能的工作,如外部命令。
的收益
语句,在另一方面,设置 $?
的价值。通常那将被设置为0表示成功,1为失败,或用于指定一种失败的一些其它值。把它看成是一个状态code,不是一般的价值。很可能,这将只支持值从0到255。
试试这个:
#!/ bin / sh的DIV3(){
EXPR $ 1%3 = 0#输出0或1的
}D = $(DIV3 1)
回声$ d个
请注意,我已经也改变了的从#!的/ usr / bin中/ env的SH
到#!/ bin / sh的
。在#!的/ usr / bin中/ env的
招调用一个跨preTER(如 perl的),您想通过
$ PATH找到
。但是,在这种情况下, SH
将总是的是 / bin / sh的
(系统会以各种方式突破,如果不是)。唯一的理由写#!的/ usr / bin中/ env的SH
是,如果你想使用任何 SH
命令首先发生出现在你的 $ PATH
而不是标准之一。即使在这种情况下,你可能会更好指定的路径 SH
直接
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
解决方案
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.
这篇关于1:命令未找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!