Share your knowledge at the LQ Wiki.
Go Back > Forums > Linux Forums > Linux - Software
User Name
Linux - Software This forum is for Software issues.
Having a problem installing a new program? Want to know which application is best for the job? Post your question in this forum.


  Search this Thread
Old 06-04-2009, 08:52 PM   #1
LQ Newbie
Registered: Mar 2009
Posts: 6

Rep: Reputation: 1
Question 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.


Last edited by dash9; 06-04-2009 at 08:59 PM.
Old 06-04-2009, 10:36 PM   #2
Registered: Mar 2008
Location: N. W. England
Distribution: Mandriva
Posts: 359

Rep: Reputation: 170Reputation: 170
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 \'\"\(\)\$\`\ \ \$


bash, path

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Automatic special character escaping in Bash scripts? wipe Linux - Software 1 06-05-2009 06:41 PM
escaping bash shell hectorDUQUE Fedora 5 03-15-2008 06:04 AM
escaping ':' character in bash script paulyche Linux - General 2 11-07-2006 07:18 AM
Bash script - escaping whitespaces colabus Linux - Newbie 15 04-29-2006 11:58 PM
NOT escaping bash history ivanatora Linux - General 3 06-07-2005 01:17 PM > Forums > Linux Forums > Linux - Software

All times are GMT -5. The time now is 04:45 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration