Short "macro" commands to change your working directory in bash

published Nov 17, 2009 12:28   by admin ( last modified Nov 17, 2009 12:28 )

 

Summary: Make a bash script that changes directory. Put it in your home directory, name it "go_somewhere," make it executable. Execute it by typing ". go_somewhere" . Don't forget the space after the dot.

 

Currently in a Plone project, I find that I often need to go to a directory deeply nested in a source code tree. If you make a shell script with the code:

#!/bin/bash

cd /home/jorgen/buildouts/a_buildout/src/ns1.ns2/ns1/ns2/skins/ns1.ns2_custom_templates/

 

...and execute it the normal way,

go_somewhere

./go_somewhere

bash go_somewhere

the script will be executed in its own subshell and cd into "/home/jorgen/buildouts/a_buildout/src/ns1.ns2/ns1/ns2/skins" just like you wanted to, but once it's finished it returns , and well, your shell never got to "/home/jorgen/buildouts/a_buildout/src/ns1.ns2/ns1/ns2/skins".

The trick is to tell bash to execute the script not in a sub shell but in the shell you are typing. You do this by first typing a dot, then a space and then the command.

. go_somewhere

 

source (contrary to the popular belief that this has to do with burgers!) is a way of getting commands to run inyour current shell (without opening a new shell, as would normally happen)



Läs mer: The Source command

Also, check out the alias command.