Bash:如何将参数与 if 语句进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10125620/
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
Bash: How to compare arguments with if statement?
提问by Awalias
I'm trying to compare an argument in bash under OSX using the following code...
我正在尝试使用以下代码在 OSX 下比较 bash 中的参数...
#!/bin/bash
if ["" == "1"]
then
echo
else
echo "no"
fi
But I keep getting the following error
但我不断收到以下错误
$bash script.sh 1
script.sh: line 3: [1: command not found
no
How do I stop it from trying to evaluate "1"?
如何阻止它尝试评估“1”?
回答by Alex
[
is a test command, so you need a space between [
and "$1"
, as well as a space between "1"
and the closing ]
[
是一个测试命令,所以你需要在[
和之间有一个空格"$1"
,以及在"1"
和结束之间有一个空格]
Edit
编辑
Just to clarify, the space is needed because [
is a different syntax of the test
bash command, so the following is another way of writing the script:
为了澄清,需要空格是因为bash 命令的[
语法不同test
,因此以下是编写脚本的另一种方式:
#!/bin/bash
if test "" == "1"
then
echo
else
echo "no"
fi
Which can be further simplified to
可以进一步简化为
#!/bin/bash
[ "" == "1" ] && echo "" || echo "no"