Home > Software design >  How can I avoid the shell script from automatically adding single quotes?
How can I avoid the shell script from automatically adding single quotes?

Time:05-25

Here is my example shell script:

#!/bin/bash

#assuming this param is obtained from outside
cmd='-c "python test.py --log_level=info"'

#full cmd
docker run xxx $cmd

The expected command should be

docker run xxx -c "python test.py --log_level=info"

however, error occurs: test.py: -c: line 0: unexpected EOF while looking for matching `"'

So I run with 'sh -x' and here is output:

  cmd='-c "python test.py --log_level=info"'
  docker run xxx -c '"python' test.py '--log_level=info"'

The full cmd is not I wondered, can you help me to solve this? Big thanks :)

CodePudding user response:

First make it easy for yourself by testing with an easier command, eg ls -- $cmd

Second, since you're using bash and not just the posix shell, use arrays!

cmd=(-c "python test.py --log_level=info")
ls -- "${cmd[@]}"
/bin/ls: cannot access '-c': No such file or directory
/bin/ls: cannot access 'python test.py --log_level=info': No such file or directory

See?

CodePudding user response:

IIUC, there is no need double quotes in your cmd, just cmd='-c python test.py --log_level=info'.

In docker run, the -c is an OPTION which means CPU shares (relative weight).

Maybe you want to exec docker run xxx sh -c ..., so the script should looks like:

cmd='sh -c python test.py --log_level=info'
docker run xxx $cmd
  • Related