Change Parent Shell’s Working Directory Programmatically

bashcd-commandshell

I want to write some code to allow me switching to some directories that I usually go to. Say this program is mycd, and /a/very/long/path/name is the directory that I want to go to.

So I can simply type mycd 2 instead of cd /a/very/long/path/name. Here I assume mycd knows 2 refers to that /a/very/long/path/name . There might also be mycd 1, mycd 3, … etc.

The problem is I have to write mycd as a shell script and type . mycd 2 to do the desired thing because otherwise the script just get executed in a child script which doesn't change anything about the parent shell that I actually care about.

My question is:

  • can I do it without using source? because . mycd assumes mycd has to be a shell script and this might also introduce some functions that I don't want.

  • can I implement it in some other programming languages?

Best Answer

make mycd a function so the cd command executes in your current shell. Save it in your ~/.bashrc file.

function mycd {
    if (( $# == 0 )); then
        echo "usage: $FUNCNAME [1|2|3|...]"
        return
    fi
    case $1 in
        1) cd /tmp ;;
        2) cd /a/very/long/path/name ;;
        3) cd /some/where/else ;;
        *) echo "unknown parameter" ;;
    esac
}
Related Question