2

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?

1 Answer 1

3
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
1
  • +1 The missing quotes really were the problem. Thanks alot! Commented Feb 25, 2013 at 18:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .