Bash - Goto Shortcut for Fast Directory Change


If you spend any considerable time in your terminal, then there are certain directories that you go to more often than others. You may depend on your terminal autocomplete to quickly type cd ~/Documents  to and press up/down until you find the match. In this article, I'm going to show how I jump to my favourite directories.

The basic idea is to create an alias for your important directories and then using that alias, you easily jump to the directory. These aliases will be added to a ~/.gotorc file that is sourced for every terminal window.

Start by creating a ~/.functions.sh and a ~/.gotorc file. This will contain some helper functions that we will create. Make sure these files are sourced on every terminal instance (this depends on what terminal/bash profile you are using. For example, if you are using Zsh, then you do this by adding source $HOME/.functions.sh and source $HOME/.gotorc to the ~/.zshrc file).

Next, add the following bash commands to this ~/.functions.sh file:

# Generic def function
def() {
	if [ "$1" = "goto" ]; then
		def_goto "${@:2}"
	fi
}

# Generic under function
undef() {
	if [ "$1" = "goto" ]; then
		undef_goto "${@:2}"
	fi
}

# Defines a new goto command
def_goto() {
	if [ -z "$1" ] || [ -z "$2" ]; then
		echo "path and shortcut are required"
	else
		LOC="$1"
		if [ "$1" = "." ]; then
			LOC=`pwd`
		fi

		CMD="alias goto_$2=\"cd $LOC\""
		echo "$CMD" >> ~/.gotorc
		source ~/.gotorc
	fi
}

# Undefines a goto command
undef_goto() {
	if [ -z "$1" ]; then
		echo "shortcut name is required"
	else
		pat="/goto_${1}/d"
		sed -i '' "$pat" ~/.gotorc
		source ~/.gotorc
	fi
}

# Shortcut for jumping to a directory
goto() {
	eval "goto_$1"
}

The def_goto is used to define an alias. You can define an alias by typing

def_goto someName /path/to/directory

The someName is the alias we will later use to jump the given directory. You can also use . as the path. When invoking this function, an alias with the name goto_someName is defined as cd /path/to/directory (if . was used, the current working directory that the def_goto was invoked in is automatically calculated). This alias is appended to ~/.gotorc file and the bash is resourced.

The undef_goto is used to remove the alias. The two methods def and undef are shortcuts for a more verbose usage of these functions. For instance, the example above can also be expressed as

def goto someName /path/to/directory

Now that you have an alias, you can jump to that directory using 

goto someName

That's it! Happy coding.

How do you rate this article?

1



k88.io Presents: Programming
k88.io Presents: Programming

Just another blog about programming, tricks and tutorials.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.