Time-saving Bash Techniques
If you are a nerd and love hacking away at your UNIX-like machine’s command line, then chances are you know that things can get really repetitive very quickly. One of my pet peeves is changing-directory upwards towards the root directory by typing cd ../../
or some such command. Some people alias two dots to the cd
command to go up one level, 3 dots to go up 3 levels, or whatever. To me this is clunky. I wanted something more flexible. So up
was born. up
is a Bash function that takes one argument: the number of directories you want to go up. If you do not specify an argument, up
will take you up one directory.
So if you are at /this/really/deep/directory/looking/around
, instead of typing lots of dots and slashes to get to /this/really/deep
, just type up 3
. Simple and Quick. Unless you are really, really deep, you’ll probably only ever have to type a maximum of 5 keystrokes to go up to any level, whereas with cd
, you’ll have to type ../
as many times as levels you want to go up. That’s at least 6 (5 if you leave off the trailing slash) if you want to go up only one level. There’s some Big-O notation just waiting to happen from that scenario.
Check out the code:
#! /bin/bash | |
function up () { | |
levels=$1 | |
if [ -z "$levels" ]; then | |
levels=1 | |
fi | |
# Test if $levels is a number; the -eq operator expects a number, and will | |
# output an error if one is not found. Any output the STDERR is redirected | |
# to the bit bucket (/dev/null) | |
if [ "$levels" -eq "$levels" ] 2> /dev/null; then | |
if [ "$levels" -eq "0" ]; then | |
levels=1 | |
fi | |
for (( c=1; c<=levels; c++ )) | |
do | |
cd ../ | |
done | |
else | |
echo up: expected a number, not $levels | |
fi | |
} |
Include that in your .bashrc
.
Very simple, but not without its problems. If you use the cd -
command to go to the last directory you were in, this will break that because it cd
s multiple times. A solution to that is to build a string with the corresponding number of ../
entries you want to go up, then passing that as an argument to cd
. I am sure there are more problems, and if you want to contribute to the betterment of nerdkind by improving the function, please fork my gist and issue a pull-request.