Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix shell script for checking three variables are same

Tags:

bash

shell

unix

i want to check if all three variables are same then print msg

if [ "$x1" == "$x2" == "$3" ];
 then 
 echo "all are same"
fi

I am getting this error:

[: too many arguments

like image 520
user3250373 Avatar asked Feb 26 '14 10:02

user3250373


2 Answers

You cannot compare three variables at the time. Instead, do compare them in blocks of two:

if [ "$x1" = "$x2" ] && [ "$x2" = "$x3" ];
then
   echo "all are same"
fi
like image 119
fedorqui 'SO stop harming' Avatar answered Sep 19 '22 16:09

fedorqui 'SO stop harming'


Since you are using bash, I'd recommend using

if [[ "$x1" == "$x2"  && "$x2" == "$x3" ]]; then

If you need/want to maintain POSIX compatibility using [ ... ], then you should not use ==.

if [ "$x1" = "$x2" ] && [ "$x2" = "$x3" ]; then

bash lets you use the non-standard == with [, but there's little point in mixing standard and non-standard behavior.

like image 33
chepner Avatar answered Sep 17 '22 16:09

chepner