0

The shell script is expected to call only one function, but calling both. How to fix this, the output is

both are same

both are not same

#!/bin/bash

var1=ORCL
var2=ORCL

function f1    
{  
    echo "both are same"
}

function f2
{
    echo "both are not same"
}

if [ $var1=$var2 ]; 
then
    f1  
fi

if [ $var1!=$var2 ]; 
then
    f2
fi
Bananguin
  • 7,984

2 Answers2

2

You need to add spaces.

Replace

if [ $var1=$var2 ]; 

with

if [ "$var1" = "$var2" ];

same for the second if statement.

pLumo
  • 22,565
2

spaces are required when relational operators are used in if condition

Ex:

if [ $var1 = $var2 ] ;

if [ $var1 != $var2 ] ;

Modified script

#!/bin/bash

var1=ORCL
var2=ORCL

f1()
{
echo "both are same"
}

f2()
{
echo "both are not same"
}

if [ $var1 = $var2 ];
then
        f1
fi

if [ $var1 != $var2 ];
then
        f2
fi
Gowtham
  • 169
  • Can you please elaborate on if/why this is an answer to the question/solution to the problem? – Bananguin Apr 10 '19 at 11:16
  • he didn't use spaces for the relational operators in the if condition . – Gowtham Apr 10 '19 at 11:18
  • Please improve your answer. Edit your answer to include the information, so that it explains to people why the code you posted helps with the question. – Bananguin Apr 10 '19 at 11:19
  • Hope I've added the missing information in detail. :-) – Gowtham Apr 10 '19 at 11:24
  • The reason is that [ is actually a program / builtin that takes a list of space separated arguments, followed by a final argument of ]. If you omit the spaces then $var1 != $var2 ] (4 arguments) becomes $var1!=$var2 ] (2 arguments), which is invalid. – JShorthouse Apr 10 '19 at 12:05
  • @JShorthouse perfect! .. – Gowtham Apr 12 '19 at 05:45