Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash if string = this or that [duplicate]

Trying to write a script which will read what a user has imput... I know it's basic but im stuck on the first if..

echo  "Please enter yes or no (y/n)?"
read string
if [ $string = "y" -o "n" ]
   then
      echo "User selected $string"
   else
      echo "You didn't enter y/n !!!"
fi

I would like it to be if [ $backup = "y" or "n" ]

Any ideas?

like image 399
bsmoo Avatar asked Apr 04 '13 09:04

bsmoo


People also ask

How do I compare two strings in bash?

To check if two strings are equal in bash scripting, use bash if statement and double equal to== operator. To check if two strings are not equal in bash scripting, use bash if statement and not equal to!= operator.

What does =~ mean in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

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.

How do you compare 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.


1 Answers

Use this syntax in bash :

if [ "a string" = "another one" ] ; then

# Whatever

fi

For multiple conditional statements such as OR, use:

if [ "a string" = "another one" ] || [ "$foo" = "bar" ] ; then

# Whatever

fi

bash also supports the non-standard [[ ... ]] expression, which can process a compound comparison using a single command, rather than 2 [ commands:

if [[ "a string" = "another one" || $foo = "bar" ]]; then

# Whatever

fi
like image 53
Halim Qarroum Avatar answered Oct 05 '22 07:10

Halim Qarroum