33

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 Answers 4

60

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

Sign up to request clarification or add additional context in comments.

3 Comments

Obviously "A" is a stand-in for something more complex and the OP puts it in quotes. Could you please clarify that lack of quotes around it in your statements? For instance the impact of spaces or at least just be explicit about the need or lack of need for quoting?
Quotes are required by POSIX. Bash's tests [[ ]] don't need it.
Presumably if the pattern that $1 was intended to match (i.e. A) included spaces then quotes would be required? For instance if A was "foo bar" then if [[ $1 == foo bar ]]; would not work? If it does work given the usual assumptions about shell scripting and coding I think a statement that it works (and hopefully why) would be great. If you could clarify this properly and also add it to the answer @Gilles_Quenot this answer would be improved.
6

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

Comments

4

Try putting a space between "A" and ].

Comments

4

You need a space after "A"

if [ "$1" -eq "A" ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.