Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape quotes and pipe in bash string

Tags:

bash

How to escape quotes and pipe?

#!/bin/bash
set -x
MYCMD="VBoxManage showvminfo --machinereadable $1 \| grep \'VMState=\"poweroff\"\'"
echo "`$MYCMD`"

Executed command :

++ VBoxManage showvminfo --machinereadable d667 '|' grep '\'\''VMState="poweroff"\'\'''

And finally getting this error:

Syntax error: Invalid parameter '|'
like image 302
Jonas Avatar asked Jan 17 '17 18:01

Jonas


1 Answers

You don't; you would need to use eval to embed an arbitrary pipeline in a regular string parameter.

MYCMD="VBoxManage showvminfo --machinereadable \"$1\" | grep 'VMState=\"poweroff\"'"
eval "$MYCMD"

However, this is not recommended unless you are certain that the value of $1 will not cause problems. (If you need an explanation of what those risks might be, then you should not be using eval.)

Instead, define a shell function:

mycmd () {
    VBoxManage showvminfo --machinereadable "$1" | grep 'VMState="poweroff"'
}

mycmd "$1"
like image 71
chepner Avatar answered Nov 14 '22 22:11

chepner