string 在 Bash 中比较两个字符串时出现“找不到命令”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19733437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting "command not found" error while comparing two strings in Bash
提问by EpsilonAlpha
My whole Script is currently this:
我的整个脚本目前是这样的:
#!/bin/sh
clear;
blanko="";
# Dummy-Variablen
variable=Testvariable;
if [[$variable == $blanko]];
then
echo "Nichts da!"
else
echo $variable
fi
and if i enter
如果我输入
TestSelect.sh
i get
我明白了
/usr/bin/TestSelect.sh: line 6: [[Testvariable: command not found
Testvariable
how can i fix this?
我怎样才能解决这个问题?
回答by anubhava
This is problem:
这是问题:
if [[$variable == $blanko]];
Spaces are required inside square brackets, use it like this:
方括号内需要空格,像这样使用它:
[[ "$variable" == "$blanko" ]] && echo "Nichts da!" || echo "$variable"
回答by codeforester
On a related note, spaces are required around [ ]
as well:
在相关说明中,周围也需要空格[ ]
:
if [ "$variable" = "$blanko" ]; then
# more code here
fi
Note that variables do need to be enclosed in double quotes inside [ ]
to prevent word splitting and globbing. Double quotes also help when either of the variables being compared is not set - shell will throw a syntax error otherwise.
请注意,变量确实需要用双引号括起来,[ ]
以防止分词和通配符。当被比较的任何一个变量未设置时,双引号也有帮助 - 否则 shell 将抛出语法错误。
Look at the following post to understand why we need spaces around [ ]
:
查看以下帖子以了解为什么我们需要空格[ ]
:
Another related post that talks about other syntax elements that need spaces as well:
另一篇讨论其他需要空格的语法元素的相关文章:
Finally, this post talks about the difference between [[ ]]
and [ ]
:
最后,这篇文章谈到的区别[[ ]]
和[ ]
:
Related:
有关的:
回答by ankit
Just use #!/bin/bash
on tope of script if you are using bash scripting like: if [[ $partition == "/dev/sda2" ]]; then
to compare string and run script with ./scriptname.sh
or bash scriptname.sh
#!/bin/bash
如果您使用 bash 脚本,则只需在脚本顶部使用,例如:if [[ $partition == "/dev/sda2" ]]; then
比较字符串并使用./scriptname.sh
或运行脚本bash scriptname.sh
回答by Danny
If your script runs on your local with /bin/bash
but not on your container with sh
, then consider adding bash to your container by apk add --no-cache bash
.
如果您的脚本在您的本地运行,/bin/bash
但不在您的容器上运行sh
,那么请考虑通过 .bash 将 bash 添加到您的容器中apk add --no-cache bash
。