0

I checked similar questions and tried the answers given, no luck there.

I'm using WSL and trying to do what ought to be simple. Take a windows path and format it, letting me cd to that directory with this script, let's call it cdw.

The script:

#!/bin/bash

input_path="$1"

Replace backslashes with forward slashes

new_path="${input_path//\//}"

Replace drive letter with linux mount path

new_path="${new_path/Z://mnt/z}"

echo "$new_path" cd "$new_path"

However, trying ./cdw.sh 'Z:\test' echoed the expected $new_path but does not cd there:

user1: /mnt/z $ ./cdw.sh 'Z:\test'
/mnt/z/test
user1: /mnt/z $

Is there something really simple I'm missing here?

3 Answers3

2

A script runs in a subshell. Changing a directory in a subshell doesn't propagate to the parent shell.

Either source the script

. csw.sh 'X:\test'

or use a function instead of a script (declare it in your .bashrc file if you want it to exist every time):

csw() {
...  # The code goes here
}
choroba
  • 10,313
0

If you change the current directory inside a script, the current directory outside the script will not change, as the script is run by a separate instance of the shell.

Instead of simply running your script, try to source it; then it will be executed in the current instance of the shell, without spawning a new one.

Type:

. ./cdw.sh 'Z:\test'

(yes, the . at the beginning of the line is a command). It should work.

raj
  • 11,409
0

Just use wslpath from WSL then there is no need to convert your path.

Usage:
    -a    force result to absolute path format
    -u    translate from a Windows path to a WSL path (default)
    -w    translate from a WSL path to a Windows path
    -m    translate from a WSL path to a Windows path, with '/' instead of '\'

EX: wslpath 'c:\users'

Example:

cd $(/usr/bin/wslpath 'Z:\test')
Terrance
  • 43,712