Kaushik Kalyanaraman
Kaushik Kalyanaraman

Reputation: 25

Bash: unexpected behavior using a variable containing directory with escaped spaces

This is a follow up to https://apple.stackexchange.com/questions/52459/ and is about an unexpected behavior in bash. To summarize what's in that link, the problem is to copy the current directory in Terminal to a temporary variable, say the pasteboard, and use that to switch directory in a different Terminal window. The solution provided there pretty much nails it in the most efficient way! However, when I actually try changing directories using this temporary variable with the correctly escaped directory name, it seems to not work right in bash.

My minimum working example is as follows:

alias cwd='printf "%q/\n" "$(pwd)"'

Now in a terminal:

>$ mkdir tmp
>$ cd tmp
>$ mkdir test\ dir
>$ cd test\ dir
>$ cwd | pbcopy

In a new terminal:

>$ echo "$(pbpaste)"
/Users/foo/tmp/test\ dir/
>$ cd $(pbpaste)
-bash: cd: /Users/kaushik/tmp/test\: No such file or directory
>$ cd "$(pbpaste)"
-bash: cd: /Users/kaushik/tmp/test\ dir/: No such file or directory

I'm quite at loss in trying to figure out what I'm doing wrong. The only thing I'm certain of is that this is a bash problem and not something that's cropping up on OS X.

Thanks for your help on this and, by the way, it turns out that I had to finally, after all these many years, end up writing my first stack overflow post!

Upvotes: 0

Views: 150

Answers (1)

Amadan
Amadan

Reputation: 198324

Copied from comments: The linked answer specifically asks for the escaped PWD suitable for pasting, but you want a programmatic input where escaping is counter-productive. Just do pwd | pbcopy and cd "$(pbpaste)".

EDIT:

(To be honest, I presumed you would need to escape it explicitly since that's how I create a directory with spaces using pwd.)

The issue is that command-line parser only does one pass of unescaping. In case of cd foo\ bar, the space is unescaped. In case of cd $(pbpaste), there is nothing to unescape; then pbpaste's literal output is put into the argument list.

Upvotes: 1

Related Questions