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:


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/

function cdup() {

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

	if [ $CDUP_ERROR -eq 0 ]; then
		# Set cd up string
		# Run the command
		for (( i=1; i<=$1; i++ )); do	
		cd $CDUP_CMD

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/

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”.