0

i have a file called MYNAME in path /root/user/ which has some value say SSS_14_10_1992

when the values exists in file the below code works fine but when the file is empty , then the below mentioned error is thrown

i am reading this value from file and matching it wildcard and doing something , when the file has some value the below code works fine , when the file is empty then i am getting conditional error

Below is my code

var=$(cat /root/user/MYNAME)

echo $var

su - uname<<!
pwd

if  [ -z "$var" ]; then
   echo "NAME SHOULD BE PROVIDED IN MYNAME FILE"
else
   if [[ $var == SSS_14_10* ]]
     then
     echo "value is matched"
   else
     echo "value has not matched"
   fi
fi
!    

when the file is empty i am getting the below error:

: conditional binary operator expected
: syntax error near `SSS_14_10*'
: `   if [[  == SSS_14_10* ]]'
5
  • Try putting var=$(cat /root/user/MYNAME) after su. Not sure if the variables defined for one user would withstand a su command. I guess it doesn't. Commented Jan 25, 2018 at 10:35
  • Also you could replace the assignment using var=$(</root/user/MYNAME) Commented Jan 25, 2018 at 10:38
  • are you trying to "match" when the right-hand-side expression is SSS_14_10* (the *)? Use =~ instead. (or is it ~=?) . Good luck. Commented Jan 25, 2018 at 13:53
  • @sjsam thanks for the reply if i put it inside su it's throwing error like to put that outside subshell Commented Jan 26, 2018 at 3:41
  • @shelter thanks for the reply , as u side i am trying to do match with wildcard on right hand side Commented Jan 26, 2018 at 3:42

2 Answers 2

3

Try to compare "$var" (with quotes) instead of $var (without quotes). This way if the variable is empty you're just comparing "".

Sign up to request clarification or add additional context in comments.

Comments

2

Don't generate code dynamically like this. Pass the value of $var as a parameter to the script run by su.

var=$(cat /root/user/MYNAME)

echo "$var"

su - uname<<'!' "$var"
pwd

if  [ -z "$1" ]; then
   echo "NAME SHOULD BE PROVIDED IN MYNAME FILE"
elif [[ $1 == SSS_14_10* ]]; then
   echo "value is matched"
else
   echo "value has not matched"
fi
!    

Note the single quotes around the here-doc delimiter; this ensures the here document is seen as-is by su, so that nothing further needs escaping.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.