[SOLVED] cd wslpath as bash function shell quoting problems

Issue

When using wsl (windows subsystem for linux) I often want to change directory to a windows directory. wslpath takes a windows directory like C:\Windows and converts it to the wsl version /mnt/c/Windows. With a bit of quoting a construct like this works well (although I suspect there are edge cases):

cd "`wslpath 'C:\Windows'`"

What I want to do is convert this into a bash function that I can put into my .bashrc file to make it a bit easier to type. I want to be able to type something like:

wcd 'C:\Windows'

The problem is quoting all these quotes so I get what I want. This option fails:

wcd ()
{
  cd "`wslpath '$1'`"
}

That one was never going to work but I was more hopeful about:

wcd ()
{
  cd \"\`wslpath \'$1\'\`\"
}

That’s about my limit with shell quoting but I’m sure it should be possible to get this to work properly.

Solution

The single quotes prevent variable expansion, so '$1' produces the literal string $1.

The command substitution is a command boundary, so you can say

wcd () { cd "`wslpath "$1"`"; }

without bumping into what admittedly can look like the second quote closing the string started by the first opening quote, instead of nesting, which you otherwise generally cannot do.

… Though the vastly preferred modern command substitution syntax should definitely be used in any new code instead;

wcd () { cd "$(wslpath "$1")"; }

Kudos for taking care to quote your arguments properly!

Answered By – tripleee

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *