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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:58:09  来源:igfitidea点击:

use conditional in bash script to check string argument

linuxbashshellterminalsh

提问by user1535776

I am trying to write my shell script thing.shso 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

解释

回答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 运算符用于整数。正如其他人提到的,空格在 ']' 之前确实很重要。

See here: http://tldp.org/LDP/abs/html/comparison-ops.html

见这里:http: //tldp.org/LDP/abs/html/comparison-ops.html