bash shell test comman

gdf

New Member
Joined
Mar 1, 2022
Messages
29
Reaction score
2
Credits
287
8 var1='hello'
9 var2=''
10 if [ -n $var1 ];then
11 echo $?
12 echo "the string '$var1' is not empty"
13 else
14 echo "the string '$var1' is empty"
15 fi
16
17 if [ -n $var2 ];then
18 echo "the string '$var2' is not empty"
19 else
20 echo "the string '$var2' is empty"
21 fi


the out put is

0
the string 'hello' is not empty
the string '' is not empty



$var2 should be empty, I can't understand why command " -n $var1 " in line 17 made line 18 done. Could you help me?


Thanks!
 


Yes, the problem is in your if statements.
You haven't put double quotes around your variable names when de-referencing their values.
e.g.
Double quoting variables in the if statements:
Bash:
#!/usr/bin/env bash
var1='hello'
var2=''

if [ -n "$var1" ];then
  echo "the string '$var1' is not empty"
else
  echo "the string '$var1' is empty"
fi

if [ -n "$var2" ];then
  echo "the string '$var2' is not empty"
else
  echo "the string '$var2' is empty"
fi

That should fix your problem!
 
Last edited:
Yes, the problem is in your if statements.
You haven't put double quotes around your variable names when de-referencing their values.
e.g.
Double quoting variables in the if statements:
Bash:
#!/usr/bin/env bash
var1='hello'
var2=''

if [ -n "$var1" ];then
  echo "the string '$var1' is not empty"
else
  echo "the string '$var1' is empty"
fi

if [ -n "$var2" ];then
  echo "the string '$var2' is not empty"
else
  echo "the string '$var2' is empty"
fi

That should fix your problem!
Got it! Thank you very much!!!!
 

Members online


Top