Make pwd print escape character

I decided I wanted to have the cd command print my full working directory after each cd command, so I put this cw command in .bashrc as a function.

cw ()
{
       cd "${1}"
       pwd
}

While this works I would like pwd to print escapes when a space in a directory name exists. This would then make it easy for me to copy and paste as opposed to putting it in quotes.

> mkdir -p /tmp/foo\ bar/baz
cd /tmp/
> cw foo\ bar/baz/
/tmp/foo bar/baz
> 

I would prefer the output to be:

/tmp/foo\ bar/baz

unfortunately pwd does not have any option for this.

How about:

cd ()
{
    cd "$@"
    echo ${PWD// /\\ }
}

I used "$@" instead of "$1" just in case you wanted to use -L or -P with cd

Thanks, that works.

I would like to have used cd as the function name but using cd as the function calls cd which is now the function, i.e. loop and stuck.

cd is a builtin so cannot provide the full path to "cd". I imagine an alias would have the same problem?

Why not alias it:

alias cd="cw"

As long as you dont have shopt -s expand_aliases in your cw function it should be OK. BTW you can use \cd at the prompt to use the builtin cd (bypassing the alias).

You can use the "builtin" builtin to call the cd builtin from within the cd function:

builtin cd

Regards,
Alister

1 Like

Perfect. the "builtin cd" is what I needed and placed it in the function and it works. I was having the same loop problem using an alias and did not have the "shopt -s expand_aliases" option.

So the function needs to be like this to work.

cd ()
{
        builtin cd "${@}"
        echo ${PWD// /\\ }
}

And no need for the alias.

Thanks very much to you both!

Nice alister, thanks.

Never had call to use builtin, as you can probably tell I don't really like the idea of alias myself, I'd rather have the shell do what I type.

I don't think I've ever used it myself, but I happened to be aware of it. There's also a 'command' builtin to bypass functions and builtins and go straight to $PATH lookup (assuming there are no slashes in the command name).

Now ... if someone defines a function named 'builtin' or 'command', the universe will probably implode. :wink:

Regards,
Alister

1 Like