Linux 在 bash 脚本中使用条件来检查字符串参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14763608/
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
use conditional in bash script to check string argument
提问by user1535776
I am trying to write my shell script thing.sh
so that upon making it an executable and running it with the single letter ``A" like so:
我正在尝试编写我的 shell 脚本,thing.sh
以便在使其成为可执行文件并使用单个字母“A”运行它时,如下所示:
$ ./thing.sh A
I get the output
我得到输出
A
If argument 1 is not A, I want the output
如果参数 1 不是 A,我想要输出
Not A
Here is my code so far :
到目前为止,这是我的代码:
#!/bin/bash
if [ "" -eq "A"]
then echo "A"
else echo "Not A"
fi
which returns, no matter what I enter,
无论我输入什么,它都会返回,
./thing.sh: line 3: [:missing `]'
Not A
I am trying what I hoped would check something with one or several letters and compare it against the letter A; could someone tell me what I am missing to get this to work? Thank you
我正在尝试我希望用一个或几个字母检查某些内容并将其与字母 A 进行比较的方法;有人可以告诉我我缺少什么才能让它发挥作用吗?谢谢
采纳答案by Gilles Quenot
What about the shorter :
更短的呢:
#!/bin/bash
[[ == A ]] && echo "A" || echo "not A"
?
?
And a beginner version (identical logic) :
和初学者版本(相同的逻辑):
#!/bin/bash
if [[ == A ]]; then
echo "A"
else
echo "not A"
fi
Like Scott said, you have a syntax error (missing space).
就像斯科特说的,你有一个语法错误(缺少空格)。
explanations
解释
- I use boolean logic here.
[[ $1 == A ]]
is executed, and then if its true,echo "A"
is executed, and if it's false,echo "not A"
is executed, See http://mywiki.wooledge.org/BashGuide/TestsAndConditionals [[
is a bash keyword similar to (but more powerful than) the[
command. See http://mywiki.wooledge.org/BashFAQ/031and http://mywiki.wooledge.org/BashGuide/TestsAndConditionalsUnless you're writing for POSIX sh, I recommend[[
.
- 我在这里使用布尔逻辑。
[[ $1 == A ]]
被执行,然后如果为真,echo "A"
则执行,如果为假,echo "not A"
则执行,参见http://mywiki.wooledge.org/BashGuide/TestsAndConditionals [[
是一个 bash 关键字,类似于(但比[
命令更强大)。请参阅http://mywiki.wooledge.org/BashFAQ/031和http://mywiki.wooledge.org/BashGuide/TestsAndConditionals除非您为 POSIX sh 编写代码,否则我推荐[[
.
回答by Scott
Try putting a space between "A"
and ]
.
尝试在"A"
和之间放置一个空格]
。
回答by Fred Thomsen
You need a space after "A"
“A”后需要一个空格
if [ "" -eq "A" ]
回答by Geoff Gustafson
Change the first line to:
将第一行更改为:
if [ "" == "A" ]
The -eq operator is for integers. And as someone else mentioned, the space does matter before the ']'.
-eq 运算符用于整数。正如其他人提到的,空格在 ']' 之前确实很重要。