1

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?

2
  • Do you really need VMID empty to be output? Would the lack of any other output be sufficient to indicate that it was empty?
    – chepner
    Commented May 30, 2020 at 12:37
  • 1
    Also, does run_prog have a non-zero exit status if it fails to produce any output? You could test that instead of explicitly checking the contents of the variable. VMID=$(./run_prog) && vim-cmd vmsvc/power.off "$VIMD".
    – chepner
    Commented May 30, 2020 at 12:39

1 Answer 1

5

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.