1:未找到命令
我正在 Bash 中编写一个除以三的函数,它不允许我将变量设置为数字。
fizzy.sh:
#!/usr/bin/env sh
div3() {
return `$1 % 3 -eq 0`
}
d=div3 1
echo $d
示例:
$ ./fizzy.sh
./fizzy.sh: line 7: 1: command not found
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Bash 函数通常通过将值打印到标准输出来“返回”值,调用者可以使用
或
捕获它们,这使得函数像外部命令一样工作。
另一方面,
return
语句设置$?
的值。通常,成功时设置为 0,失败时设置为 1,或者设置为指定失败类型的其他值。将其视为状态代码,而不是一般值。这可能只支持 0 到 255 之间的值。请尝试以下操作:
请注意,我还更改了 shebang 行从
#!/usr/bin/env sh
到#!/bin/sh
。当调用您想要通过 $PATH 定位的解释器(例如perl
)时,通常会使用#!/usr/bin/env
技巧>。但在这种情况下,sh
将始终位于/bin/sh
中(如果不是,系统会以各种方式崩溃)。编写#!/usr/bin/env sh
的唯一原因是如果您想使用恰好出现在$PATH< 中的任何
sh
命令/code> 而不是标准的。即使在这种情况下,您最好直接指定sh
的路径。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
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:
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 asperl
) 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 whateversh
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 tosh
directly.该
行是罪魁祸首,因为您将字符串 div3 分配给环境变量 d 并尝试执行 1。为避免这种情况,请使用反引号来分配评估结果:
然后,评估函数中会出现另一个错误。您需要对参数运行测试,而不是尝试将它们作为命令进行评估:
仍然没有输出,但也没有错误。实际上,您的预期产出是多少?
The
line is the culprit because you assign the string div3 to the env variable d and try to execute 1. To avoid this, use backticks to assign the result of the evaluation instead:
Then, another error occurs in your evaluation function. You need to run test on your arguments instead of trying to evaluate them as a command:
Still no output, but no errors either. What would your expected output be, actually?
注意,return 只是设置 $? 的值?对于函数
要返回值,只需打印它。
Note, return just sets the value of $? for the function
to return value, just print it.