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?

dwjbosman
  • 469

2 Answers2

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[@]}"
Freddy
  • 25,565
-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
Jim L.
  • 7,997
  • 1
  • 13
  • 27