Bash:虚假的“未找到命令”消息(我认为)
我正在尝试在 Bash 中编写一个简单的实用函数,它将在给定目录中执行“操作”。所以我基本上抽象了“进入目录,做某事,然后回来”模式。
inDir() {
if [$# -le 1]; then
return;
else
local dir="$1";
local action="$2";
local cwd=`pwd`;
if [ -d "$dir" ]; then
cd "$dir";
$action;
cd "$cwd";
else
return;
fi
fi
}
不幸的是,当我运行这个程序时,我得到了一个我认为是虚假的错误,并且我不确定它来自哪里。例如:
$ inDir "/tmp" "touch hi"
正确创建文件 /tmp/hi,但也给出错误:
[2: command not found
我不确定这对读取错误是否重要,但我的提示符以“[”开头。
有什么帮助吗?
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory. So I am basically abstracting the "go to a directory, do something, and come back" pattern.
inDir() {
if [$# -le 1]; then
return;
else
local dir="$1";
local action="$2";
local cwd=`pwd`;
if [ -d "$dir" ]; then
cd "$dir";
$action;
cd "$cwd";
else
return;
fi
fi
}
Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from. For example:
$ inDir "/tmp" "touch hi"
correctly creates the file /tmp/hi, but also gives the error:
[2: command not found
I'm not sure if this matters to reading the error, but my prompt starts off with a "[".
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不管它看起来像什么,“[”实际上是一个名为
test
的命令,因此:应该是:
注意“[”和下一段代码之间的空格。如果没有它,代码读起来
我认为显然是错误的。您还需要在右方括号之前有一个空格,它不是命令,而是分隔符。
Despite what it might look like, '[' is actually a command called
test
, so:should be:
Note the space between the '[' and the next bit of code. Without it, the code reads as
which I think is obviously wrong. You also need a space before the closing square-bracket, which isn't a command, but is a delimiter.
@NeilButterworth 答案是正确的。
bash 试图解决上述常见错误,并引入了内置的数字比较结构
(())
。例如:
[]
结构的优点是它使用常规比较运算符(例如 <、>、==)并且不需要[]
那样的空间做。对于字符串比较,有类似的结构
[[]]
@NeilButterworth answer is correct.
bash tries to solve the above common error and introduces built-in numeric compare structure
(())
.For example:
The advanteges over
[]
structure is that it used regular compare operators (e.g. <, >, ==) and doesn't requires space as[]
does.For string comparison there's similar structure
[[]]
如果使用子 shell,生活会更简单
对当前 shell 没有影响。
Life is simpler if you use sub-shells
Has no effect on the current shell.
这可能会帮助您处理更复杂的参数
所以现在您可以执行以下操作:
This may help you with handling more complex arguments
So now you can do something like: