在bash脚本中使用条件检查字符串参数 [英] use conditional in bash script to check string argument
问题描述
我正在尝试编写我的shell脚本 thing.sh
,以便在使其成为可执行文件并以单个字母"A"运行它后,如下所示:
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:
$ ./thing.sh A
我得到了输出
A
如果参数1不是A,则需要输出
If argument 1 is not A, I want the output
Not A
到目前为止,这是我的代码:
Here is my code so far :
#!/bin/bash
if [ "$1" -eq "A"]
then echo "A"
else echo "Not A"
fi
无论输入什么,都会返回
which returns, no matter what I enter,
./thing.sh: line 3: [:missing `]'
Not A
我正在尝试我希望用一个或几个字母检查的东西并将其与字母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
推荐答案
简短一点:
#!/bin/bash
[[ $1 == A ]] && echo "A" || echo "not A"
?
和初学者版本(相同的逻辑):
And a beginner version (identical logic) :
#!/bin/bash
if [[ $1 == A ]]; then
echo "A"
else
echo "not A"
fi
就像Scott所说的那样,您遇到语法错误(缺少空格).
Like Scott said, you have a syntax error (missing space).
- 我在这里使用布尔逻辑.
[[$ $ == A]]
,然后执行,如果为真,则执行echo"A"
,如果为假,则执行echo"not A"
已执行,请参见 http://mywiki.wooledge.org/BashGuide/TestsAndConditionals -
[[
]是一个bash关键字,与[
命令类似(但功能更强大).请参阅 http://mywiki.wooledge.org/BashFAQ/031 和
- 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/031 and http://mywiki.wooledge.org/BashGuide/TestsAndConditionals Unless you're writing for POSIX sh, I recommend[[
.
这篇关于在bash脚本中使用条件检查字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!