Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use conditional in bash script to check string argument

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

like image 336
user1535776 Avatar asked Feb 08 '13 00:02

user1535776


People also ask

How do I test a string in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

How do you check if two strings are equal in shell script?

Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.


Video Answer


2 Answers

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

  • 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 [[.
like image 132
Gilles Quenot Avatar answered Sep 23 '22 07:09

Gilles Quenot


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

like image 34
Geoff Gustafson Avatar answered Sep 21 '22 07:09

Geoff Gustafson