Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
/home/helpermethod/foo[b]ar/foo/bar

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"
/home/helpermethod/foo[b]ar

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
add comment

1 Answer

up vote 3 down vote accepted
stripped_path=${path%"$basename"/*}/$basename

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"

Or

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

Your Answer

 
discard

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.