2

I have the following bash script:

set -ex
X="bash -c"
Y="ls -al"

I want to execute (notice the double quotes):

bash -c "ls -al"

The following does not work:

C=$X\ $Y
$C

This gives as output

+ X='bash -c'
+ Y='ls -al'
+ C='bash -c ls -al'
+ bash -c ls -al

There are no double quotes around ls -al

I tried this:

C=$X\ \"$Y\"

But that doesn't work:

+ X='bash -c'
+ Y='ls -al'
+ C='bash -c "ls -al"'
+ bash -c '"ls' '-al"'

How to correctly concatenate Y to X while keeping double quotes around Y?

0

2 Answers 2

4

You could use an array variable for C:

X="bash -c"
Y="ls -al"
C=($X "$Y")
"${C[@]}"

Note that $X is not quoted since we have one command and one parameter.

Or the short version:

C=(bash -c "ls -al")
"${C[@]}"
-1

Either of these methods will work, and I'm sure there are more.

X="bash -c"
Y="ls -al"

Z="$X \"$Y\""
echo $Z

Z=$(printf '%s "%s"' "$X" "$Y")
echo $Z
2
  • How do you execute it?
    – Freddy
    Commented Jun 27, 2019 at 23:47
  • @Freddy echo $Z | sh works. Or eval $Z.
    – Jim L.
    Commented Jun 27, 2019 at 23:51

Not the answer you're looking for? Browse other questions tagged .