Problem if statement

echo "Enter the variable: " "
read var1
echo " "
for i in ib eb atm
do
if [ $var1 = $i ]; then
mv properties environment.properties
break
else
 echo "No changes to $var1 "
fi
done

When i run and enter the eb it's not working.Any suggestions please..

What do you mean by "it's not working"? Do you mean you're getting a syntax error for mismatched quotes on the first line of your script?

What are you expecting to happen?

What is happening?

What OS are you using?

What shell are you using?

1)I am using AIX operating system.
2) I am using bash shell
3)Entered value is ib or eb or atm then it should mv properties environment.properties else it should not exit from the script. It should move next step in the script.

I didn't see any error messages but my logic is not working. When I compare if [ $var1 = $i ]

Var1= eb it should mv the file but it is going else place.

Enter the variable:
eb

o/p:
No changes to eb

echo "Enter the variable: "
read var1
echo " "
for i in ib eb atm
do
if [[ $var1 == $i ]]; then
mv properties environment.properties
break
else
 echo "No changes to $var1 "
fi
done

If you enter eb
then it prints 'No changes' for i = ib, but then runs the mv for i = eb

There are several problems with this:

first, test s string comparison operator is not "=" but "==", as SriniShoo has already stated;

second, you should quote your variables: if "$var" contains whitespace, your command is going to fail with a syntax error otherwise:

if [ "$var1" == "$i" ]; then

In addition your logic is flawed: the for-loop will try one possible value after the next and for every failed attempt print "no changes". Hence, if you enter "atm" the output will read something like:

No changes to atm
No changes to atm

and your file will get moved - or not, depending on it being there in first place, otherwise you will get an error.

You might want to make the output of your script somewhat better understandable.

I hope this helps.

bakunin

A better way of doing this would be:

case $var1 in 
  (ib|eb|atm) echo match ;;
  (*) echo no match ;;
esac

Actually, it is a single = . See test: operands

1 Like

Thanks a lot Scrutinizer.It's working as expected..