LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   filename escaping in bash (http://www.linuxquestions.org/questions/linux-software-2/filename-escaping-in-bash-730784/)

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:
Code:

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

Like this:
Code:

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. ;)

Thanks!

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.
Code:

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

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



All times are GMT -5. The time now is 09:47 AM.