Yuku's answer only works if you are the only user of your script, while Dennis Williamson is great if you are mostly interested in printing lines and expecting that they don't have quotation marks.
Here's a version that can be used if you want to pass all arguments as a single large quote argument to the -c bash or su parameter:
#!/bin/bash C='' for i in "$@"; do i="${i//\\/\\\\}" C="$C \"${i//\"/\\\"}\"" done bash -c "$C"
So, all arguments get a quote around them (harmless if not before, for this purpose), but we also avoid any screens, and then avoid quotes that were already in the argument (syntax ${var//from/to} performs a global substring of a substring).
You could, of course, only quote material that already had spaces in it, but here it does not matter. One of the possibilities of a script like this is to have a specific predefined set of environment variables (or, with su, to run the material as a specific user without this mess for double quoting).
Update. I recently had a reason to do this with POSIX with minimal markup, which will lead to this script (the last printf prints the command line used to invoke the script, which you must have copy-paste to invoke with equivalent arguments):
#!/bin/sh C='' for i in "$@"; do case "$i" in *\'*) i=`printf "%s" "$i" | sed "s/'/'\"'\"'/g"` ;; *) : ;; esac C="$C '$i'" done printf "$0%s\n" "$C"
I switched to '' , since shells also interpret things like $ and !! at "" -quotes.
unhammer Jan 04 '12 at 7:15 2012-01-04 07:15
source share