Score:0

Can't cd to path variable in simple bash script

ru flag

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?

Kulfy avatar
mz flag
Does this answer your question? [Why doesn't "cd" work in a shell script?](https://askubuntu.com/questions/481715/why-doesnt-cd-work-in-a-shell-script)
Score:2
tm flag

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
}
Score:0
cn flag
raj

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.

Score:0
id flag

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')
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.