Is it possible to have bash escape spaces in pwd? I'd like to copy the current directory to the clipboard, something like: pwd | pbcopy. However, pwd does not escape the space, so something in "Application Support", for example, doesn't copy correctly. I don't seem to remember this always being the case, so I could have boffed something. Using iTerm2.

Is there bash setting to escape everything? having trouble searching, too many questions/topics about Spaces.app or esc.

Current:

$ pwd
/Library/Application Support/Google Earth/


Preferred:

$ pwd
/Library/Application\ Support/Google\ Earth/


Already seen posts: Copying the current directory&#39;s path to the clipboard and How to cd to a directory with a name containing spaces in bash?, which do not address this. I would have made a comment in the former, but I don't have the privileges.
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 &gt;(pbcopy)'