Log in

No account? Create an account
Clip Man


Daniel Einspanjer's journal

Data warehousing, ETL, BI, and general hackery

Previous Entry Share Next Entry
Bash functions for going up to a directory
Clip Man
Sometimes, if I'm in a really deep directory, I don't want to cd from / nor do I want to cd ../../../..
I just want to either go up 5 directories, or maybe I want to go up to the parent directory "src" when I'm in /home/dre/src/projects/foo/bar/classes/org/apache/blah

This set of Bash functions lets me do that.
The first, up() will change your directory. The second will instead just print the desired directory name.  This makes it easy for you to mv a file up higher or something.

If you pass no arguments, it just goes up one directory.
If you pass a numeric argument it will go up that number of directories.
If you pass a string argument, it will look for a parent directory with that name and go up to it.
(Note, there is a small display bug there. If you give it an invalid name, cd reports the "No such file or directory" error, which is good, but it has a bogus path. Since you can't know what path they were actually trying to go to, it should just say "No such parent directory: ${yourbogusname}". I don't have time to figure that out right now though.)

Just put these functions in your ~/.bashrc file and don't forget to source it. (  source ~/.bashrc )

function up()
    if [ -z "$1" ]; then
    elif [[ $1 =~ ^[0-9]+$ ]]; then
        while [ $x -lt ${1:-1} ]; do
    cd "$dir";

function upstr()
    echo "$(up "$1" && pwd)";

  • 1

I was fixing it as fast as I could. LJ was timing out on me.

Ooh, what a useful idea. Those are going straight to my bash scripts, thank you.

I do something much lazier, but for similar effect:
alias cd.='cd ..'
alias cd..='cd ../..'
alias cd...='cd ../../..'
alias cd....='cd ../../../..'
alias cd.....='cd ../../../../..'

I put together a handful of other bash commands that I use along this handy "up" command.



  • 1