Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm pretty confused about under which circumstances do I need to escape metacharacters in pathnames. Consider the following example:

I'm in the following working directory:

$ echo $PWD

Now I want to strip off everything behind foo[b]ar. I'm using parameter substitution to perform this task:/home/helpermethod/foo[b]ar

$ path=$PWD
$ basename=foo[b]ar
$ stripped_path=${path%$basename/*}/$basename

This doesn't seem to work because the basename string needs to be properly escaped:

$ basename=foo\[b\]ar
$ stripped_path=${path%$basename/*}/$basename

Okay, now I have the stripped_path I was looking for

$ echo "$stripped_path"

But if I now test if this is a valid directory

$ [[ -d $stripped_path ]]

the test command always returns false (i.e. a return value != 0). What's the problem here? Do I need to unescape the stripped_path?

share|improve this question
up vote 3 down vote accepted

Use double quotes to do literal string matching as opposed to pattern matching. One of the cases where you need to quote variables. Another case is in your:

echo $PWD

above which should have been:

echo "$PWD"

Or even better:

printf '%s\n' "$PWD"


share|improve this answer
+1 The missing quotes really were the problem. Thanks alot! – helpermethod Feb 25 '13 at 18:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.