lets assume this is the string:


it contains both single and double quotes.

how would you pass this to a bash script as a single string ?

this is the bash script:

echo $1

it must echo


but we can not assume the string is this tiny. ultimately i plan on sending the whole


as a string to this bash script.

so i can not really escape quotes and single quotes one at a time.

  • What are you trying to do? – dawud Jun 21 '14 at 7:52
  • @dawud, only a bash script can execute things as sudo. so i am trying to save the file through a bash script. – user72685 Jun 21 '14 at 7:56
  • What environment is that? You can't use sudo, but your scripts can? – psimon Jun 21 '14 at 8:16
  • @psimon, WSGI runs as user 'apache' but uses python code which uses os.popen() to execute the bash script with sudo after apache user is added to sudoers file for the bash script only – user72685 Jun 21 '14 at 8:19
  • 1
    Make that script echo "$1" to avoid severe mangling, or rather printf %s "$1" if you want the argument to be printed out intact in all cases. See unix.stackexchange.com/questions/131766/… – Gilles 'SO- stop being evil' Jun 21 '14 at 12:16

You can use command substitution:

oo.sh "$(cat /etc/httpd/conf/httpd.conf)"

This will run cat /etc/httpd/conf/httpd.conf and put the output (the contents of the file) into the first argument given to oo.sh. It's quoted, so it gets passed as a single argument — spaces and special characters are passed through untouched. oo.sh gets a single argument.

More broadly, though, it might be better to pass the filename into the script if possible, or to give the file contents as standard input (oo.sh < /etc/httpd/conf/httpd.conf). As well as being more standard, there's a maximum length all the command-line arguments put together can be, and a file could be longer than that. Even if it works now, if that file might grow bigger over time eventually passing the whole thing as an argument will stop working with an error "arg list too long".

You can find that limit with getconf ARG_MAX. The size varies dramatically: I have systems here with 2MB limits and 256KB limits. If your file will always be small you don't need to worry, but otherwise you should try another way of getting the data into the script.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.