Three Shortcuts to Quickly Change Directories in Linux

While working on projects in Linux, I often have to navigate through long directory paths with cd to arrive at the working directory where the most-accessed files are kept. For example:

slc@linux:~$ cd SmileForward/smileforward-backend/sfsite/smileforward/

Smart auto-complete with tab helps, but it’s still rather inefficient, especially when you have to repeat this sequence across multiple terminals (and again every time you restart the OS).

My initial reaction was to write a script with a short name:

slc@linux:~$ vim sf


cd SmileForward/smileforward-backend/sfsite/smileforward/

But this apparently doesn’t work, as the shell stays at the same directory after executing the script:

slc@linux:~$ chmod +x sf
slc@linux:~$ ./sf

After a bit of digging, I discover the problem:

Each time a script is run with dot slash “./”, a brand-new subshell is spawned from the current shell to run whatever is in the script, and then it terminates without affecting the parent shell. So the new shell does change to the specified directory, but then it terminates and control is returned to the parent shell.

To remedy this, here are three different shortcuts:

1. Run the script with . or source:

slc@linux:~$ . sf
slc@linux:~/SmileForward/smileforward-backend/sfsite/smileforward$ cd
slc@linux:~$ source sf

Running a script with . or source executes it within the current shell (without spawning a subshell).

2. Name the shortcut as an environment variable and save it in ~/.bashrc (so bash shell loads it every time a new bash shell spawns):

slc@linux:~$ vim ~/.bashrc


export sf=~/SmileForward/smileforward-backend/sfsite/smileforward
slc@linux:~$ cd $sf

3. Make an alias for the cd script (best solution)

slc@linux:~$ vim ~/.bashrc


# run the command closed by single quotes when sf is encountered
alias sf='cd ~/SmileForward/smileforward-backend/sfsite/smileforward' 
slc@linux:~$ sf

Alternatively, the alias can be:


# Run the sf script from option 1
alias sf='. ~/sf'


# cd to the sf environment variable from option 2
alias sf='cd $sf'

Hopefully this saves you some time when navigating between commonly visited directories in Linux.

Another very popular solution for changing directories is z ( I’m new to z, so it’s left up to the reader to explore.

(P.S. you can also symlink to the directory: ~/SmileForward/smileforward-backend/sfsite/smileforward/, but this leads to a less versatile result as there’s no easy way to move up to a parent directory)

One thought on “Three Shortcuts to Quickly Change Directories in Linux

Leave a Reply

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