1

lets assume this is the string:

   'a',"b"

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:

#!/bin/bash
echo $1

it must echo

'a',"b"

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

 /etc/httpd/conf/httpd.conf

as a string to this bash script.

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

user72685
  • 323
  • What are you trying to do? – dawud Jun 21 '14 at 07: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 07:56
  • What environment is that? You can't use sudo, but your scripts can? – psimon Jun 21 '14 at 08: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 08:19
  • Why don't you cat the conf file in your script to a variable? – polym Jun 21 '14 at 08:21
  • @polym, i am editing the file in question, so it has turned into a string. – user72685 Jun 21 '14 at 08:23
  • 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 http://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters – Gilles 'SO- stop being evil' Jun 21 '14 at 12:16
  • Also posted at http://stackoverflow.com/questions/24339678/how-to-pass-a-variable-to-a-bash-script-that-contains-quotes-and-single-quotes – devnull Jun 21 '14 at 13:04

1 Answers1

5

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.

Michael Homer
  • 76,565