I love bash but there's one thing that always gets me and makes me lose tons of time: quotes!
I know quite a few tricks such as using "$@" "$*" and escape characters of course, however there are some odd cases when these aren't sufficient.
Here is my problem right now; I have this script:
Code: Select all
#!/bin/bash
sanitizeq() { echo $1 | sed -e 's/"/\\\\\\\"/g'; }
cmd="sg allownet \"$1 "
i=1
while shift; do echo $1; ((i++)); [[ -n "$1" ]] && cmd+="\\\"$(sanitizeq "$1")\\\" "; done
cmd+=\"
echo "$cmd"
eval "$cmd"
Here's an example:
Code: Select all
$ an echo hello "'my' \" world" #'an' is the script's name
hello
'my' " world
sg allownet "echo \"hello\" \"'my' \\\" world\" "
hello 'my' " world
But this:
Code: Select all
$ an echo hello "'my' \\\" world"
hello
'my' \" world
sg allownet "echo \"hello\" \"'my' \\\\" world\" "
/home/mx/bin/an: eval: line 10: unexpected EOF while looking for matching `"'
/home/mx/bin/an: eval: line 11: syntax error: unexpected end of file
Of course I could add a clause to deal with '\"' in the 'sanitizeq' function but the code would still not work with '\\"', and this would go on ad infinitum. Yes, I could most certainly implement an algorithm to treat all cases but there must be a simpler way which is why I am asking for your advice.
This kind of problem is quite common when dealing with file names so it isn't a exactly extreme situation.


