Is it possible to have bash escape spaces in pwd?

Solution 1:

This command will escape spaces properly:

printf "%q\n" "$(pwd)" | pbcopy

You can alias it using something with history like cwd if you don't mind re-defining a different cwd

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

Ditch the pipe to pbcopy if you want it to work more like pwd and just print out the escaped path.


Or, to print the pwd while also copying it to the clipboard, use tee and an output process substitution:

alias cwd='printf "%q\n" "$(pwd)" | tee >(pbcopy)'

Solution 2:

pwd | sed 's/ /\\ /g'

But I'm not sure this will ultimately fix your issue. pbcopy is copying exactly what it receives on stdin.

Solution 3:

There is no built-in way to make pwd output escaped file paths, as this is generally not useful.

It does not make sense for pwd or pbcopy to be adding backslashes to what is copied. If you wanted to copy the path into a text file or web post, you would not want a backslash inserted into it.

Probably what you want to do is create as separate alias, like qwd, to print the quoted form of the current directory, or just escape the output of pbpaste, which is as easy as putting it in double-quotes:

bash-3.2$ pwd
/Users/user
bash-3.2$ cd test\ dir/untitled\ \"folder/
bash-3.2$ pwd
/Users/user/test dir/untitled "folder
bash-3.2$ pwd | pbcopy
bash-3.2$ echo "`pbpaste`"
/Users/user/test dir/untitled "folder
bash-3.2$ cd
bash-3.2$ pwd
/Users/user
bash-3.2$ cd `pbpaste`
bash: cd: /Users/user/test: No such file or directory
bash-3.2$ cd "`pbpaste`"
bash-3.2$ pwd
/Users/user/test dir/untitled "folder

Note that it is not just spaces that need escaping. Forward and backward slashes, star, question mark, ampersand, semi-colon, and other characters need escaping, too. Safest is just to use double-quotes as in the example, which will work even if the path includes double-quotes in it.

If you want to be perverse about it, you could make AppleScript quote the current directory for you:

bash-3.2$ alias qwd="osascript -e 'return quoted form of POSIX path of (POSIX file \"./\" as alias)'"
bash-3.2$ qwd
'/Users/user/test dir/untitled "folder'

Otherwise I mostly agree with Glenn, except, as above, I would alias the quoted form to qwd so as not to interfere with the normal pwd:

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