Bash script to go up several directories

I work inside terminals/shells a lot of my time. I also regularly am in the situtation where I am in a deep subdirectory like:

/home/jan/projects/myproject/vendor/SomeVendor/src/Utilities/Regex/

When I am there, I also have a regular need to go back to my “main” project dir. Normally you’d do something like this:

cd /home/jan/projects/myproject

Or this:

cd ../../../../../

Although, it takes a lot of typing to do that. Auto-completion of folder names helps a little, but I still figured there could be an easier way to achieve the same. So I created a small bash function that allows you to “cd up” a couple of directories at once just by typing out the number of the amount of dirs you want to go up, like:

cdup 5

To achieve this, I created the following bash function and saved it under /usr/local/bin/cdup.sh:

#!/bin/bash
function cdup() {
	CDUP_ERROR=0

	if [ $# -ne 1 ]; then
		CDUP_ERROR=1
		echo "Syntax: $0 <number>"
	elif ! [[ $1 =~ "^[0-9]+$" ]] ; then
		# Something other than a number was passed
		CDUP_ERROR=1
		echo "Please use a number as input, e.g. cdup 2"
	fi

	if [ $CDUP_ERROR -eq 0 ]; then
		# Set cd up string
		CDUP_STR="../"
		CDUP_CMD="`pwd`/"
		
		# Run the command
		for (( i=1; i<=$1; i++ )); do	
			CDUP_CMD=$CDUP_CMD$CDUP_STR
		done
		
		cd $CDUP_CMD
	fi
}

Because bash scripts run in their own environment, the cd itself does not change the directory of your current shell, to achieve that we have to “source” the function in our .bashrc file (located in your home dir). Simply add this line to it:

source /usr/local/bin/cdup.sh

Now, reload the adjusted .bashrc (by running source ~/.bashrc) or start a new shell and you should be able to simply cdup 5 to go up 5 directories. Obviously you can adjust the number 5 with anything you want. Hope this helps anybody else facing the same “problem”.