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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With