Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for variable to be non-empty in bash

Tags:

bash

I want to run a remote command over ssh. So, the one line command is

ssh [email protected] 'VMID=`./run_prog` && if [ -n $VMID ]; then echo "id=$VMID"; vim-cmd vmsvc/power.off $VMID; else echo "$VMID empty"; fi'

Problem is that if VMID is empty or non-empty, I see the output of vim-cmd.

id=
Usage: power.off vmid

or

34
Powering off VM:

How can I be sure that vim-cmd is executed for non-empty VMID values?

like image 643
mahmood Avatar asked Sep 16 '25 05:09

mahmood


1 Answers

The problem is that you do not quote the variable inside the if condition. You have to do it this way:

if [ -n "$VMID" ]

You might wonder why if you don't quote you face problems. Well the answer is in man test:

-n STRING
the length of STRING is nonzero
STRING
equivalent to -n STRING

So when VMID is empty, the if condition results like this:

if [ -n ]

and test will assume that you want to check if -n is an empty string. It won't undestand that you have used -n as an option. So, -n is not empty and the test passes.

If you use quotation, test will understand what you want.

If I can add a suggestion, don't use backquotes for command substitution. Use $(./run_prog) instead. Check this answer if you want more information about it.

like image 113
Francesco Avatar answered Sep 17 '25 18:09

Francesco