• We did not send an email asking for donations - please read this post.

bash shell test comman

gdf

New Member
Joined
Mar 1, 2022
Messages
12
Reaction score
1
Credits
114
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!
 


KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
7,349
Reaction score
6,339
Credits
59,574

JasKinasis

Well-Known Member
Joined
Apr 25, 2017
Messages
1,563
Reaction score
2,224
Credits
11,524
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:
OP
G

gdf

New Member
Joined
Mar 1, 2022
Messages
12
Reaction score
1
Credits
114
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!!!!
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Linux.org Hosting Donations
Consider making a donation


Top