-   Linux - Software (
-   -   filename escaping in bash (

dash9 06-04-2009 08:52 PM

filename escaping in bash
I have a file and its name includes special characters, for example: '"()$` $
I want to print a command which can be copy/pasted in a bash terminal, for example: ls '"()$` $
Obviously, this won't work, I need to escape that value.
What I'm using at the moment is the following function:

function escape {
  echo \'"$(echo "$*" | sed -e "s/'/'\"'\"'/g")"\'

Like this:

f="'\"()\$\`  \$"
echo "$f"
# The following should print a command that should have
# exactly the same effect as the one on the line above
echo echo "$(escape "$f")"

This prints:
'"()$` $
echo ''"'"'"()$` $'

Now if I run the printed echo command, it prints, as expected:
'"()$` $

My question: Is there a more elegant or a better solution than my escape() function above? Ideally it would be an internal Bash command. For example, a function which would escape exactly the special characters, and nothing more, and would produce, for the example above: echo \'\"\(\)\$\`\ \ \$ instead of printing and having to use a gazillion quotes. ;)


Kenhelm 06-04-2009 10:36 PM

In the Bash version of printf, %q quotes the argument in a way that can be reused as shell input.

f="'\"()\$\`  \$"
printf '%q ' echo "$f"

echo \'\"\(\)\$\`\ \ \$

All times are GMT -5. The time now is 08:52 PM.