0

I have a shell script and want to be able to pass commands like: bash -c "COMMAND ARGS"

set -x
cmd='bash -c "ls /lib"'
docker run --rm ubuntu:bionic $cmd

But I get

+ cmd='bash -c "ls /lib"'
+ docker run --rm ubuntu:bionic bash -c '"ls' '/lib"'
/lib": -c: line 0: unexpected EOF while looking for matching `"'
/lib": -c: line 1: syntax error: unexpected end of file

How to escape these extra quotes?

and what about if I need to get the argument from the command line, using for example ./script.sh "bash -c 'ls lib'"

set -x
cmd=$1
docker run --rm ubuntu:bionic $cmd

1 Answers1

2

Use an array, not a regular parameter, to store the command.

set -x
cmd=(bash -c "ls /lib")
docker run --rm ubuntu:bionic "${cmd[@]}"
chepner
  • 497,756
  • 71
  • 530
  • 681