use conditional in bash script to check string arg

2020-06-07 06:53发布

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

I get the output

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

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

4条回答
你好瞎i
2楼-- · 2020-06-07 07:03

What about the shorter :

#!/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

Like Scott said, you have a syntax error (missing space).

explanations

查看更多
叛逆
3楼-- · 2020-06-07 07:06

Try putting a space between "A" and ].

查看更多
Melony?
4楼-- · 2020-06-07 07:09

You need a space after "A"

if [ "$1" -eq "A" ]
查看更多
Viruses.
5楼-- · 2020-06-07 07:24

Change the first line to:

if [ "$1" == "A" ]

The -eq operator is for integers. And as someone else mentioned, the space does matter before the ']'.

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

查看更多
登录 后发表回答