Here is something I have in my Bash config that I have found useful these days. It defines a command called up that lets me move up a given number of directories. For example, up 2 is the same as cd ../.., and up 4 is cd ../../../.., and so on.
function up() {
cd $(perl -e 'print join("/" => ("..") x shift)' $1)
}
I found this somewhere online, so I am not taking credit for it. The way this works is we use Perl to create the string ../../.., or however many dots and slashes we need to reach the right parent directory. We can create that string to go up three directories by using the code
("..") x 3
to create the list
(".." ".." "..")
We then use join to insert a slash between each set of dots. This gives us code very close to what is in the function above. The key difference is the use of shift. We don’t know ahead of time how many .. strings to create, since that depends on how many directories upward we want to move. What we want to do then is pass in the number of ..‘s to create as an argument to the Perl script. By default shift will pop off the first command-line argument to the script, which will be our number.
This is how we end up with
perl -e 'print join("/" => ("..") x shift)' $1
Here $1 refers to the first argument of the up shell function. So when we use up 3 we get
perl -e 'print join("/" => ("..") x shift)' 3
which gives us
print join("/" => ("..") x 3)
print join("/" => (".." ".." ".."))
print "../../.."
That string is finally returned as the argument to cd, which moves us up the right number of directories.
Related to this are some aliases I use to treat and as a stack of directories. Bash has two commands called pushd and popd. The former will change to the given directory and put it on the stack. The latter will pop the top of the stack and move to the directory that is now at the top. So I use these aliases to those commands:
alias bd="popd"
alias cd="pushd"
alias rd="popd -n"
The mnemonic for bd is to go ‘back a directory’. The rd alias ‘removes a directory’; it takes the top directory off the stack without switching to it. This is sometimes useful when I end up deleting a directory on the stack, because then ‘bd’ will complain with an error if I try to move back to it.
The command dirs will show you the stack, starting with the current directory on the left. Once you get used to it, I think this is a useful way of moving around directories.




