HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMajor

"Up" script for moving up directories quickly

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptquicklymovingfordirectories

Problem

A long time ago I created a script for moving up directories very quickly in the command line using the command up. You can find usage notes here.

It's a very simple script with just 8 lines of source code, as follows:

if [ -z "$1" ]; then
    cd ..
else
    for i in `seq 1 $1`;
    do
        cd ..
    done
fi


I've never personally had any problems with it since I made it and started using it myself — but are there any accidental or malicious inputs (particularly with the blind injection of $1) that might cause this to do something bad that I'm not aware of?

Given that the up command isn't used for anything in any command line I'm aware of, I'd like to promote more widespread usage of this script file so that people can type up instead of cd .. all the time, saving three keystrokes (or more if they want to move up more directories) for a very common operation.

Solution

This is a decent concept, but by looping on the cd you loose some of the value of the $OLDPWD function in the shell. For example, I often use the special construct cd - in a shell, and that changes directory to the one you were in before.

Your code will make that impossible.

I would instead recommend that you instead build up a chain of ../ string values, like ../../../../ for 4 directories, and then just call cd once, which will preserve the cd - function, and the $OLDPWD.

Additionally, this would be a good feature to include as a function in your code, rather than a script. Bash shell likes functions, and they make life easier.

Finally, if someone supplies a non-number as an argument, it will do odd things.

I played with your code, and came up with:

up () {
    local count=$1
    if [ -z "$count" ]; then
        cd ..
        return
    fi

    test "$count" -eq "$count" || return 1

    local todir=""
    for i in `seq 1 $count`;
    do
      todir="../$todir"
    done
    cd $todir
}


The features of the above code I like are:

  • it is a function of the shell, so there's no additional script called.



  • it checks the value is a number, by doing a numeric comparison on the value: test "$count" -eq "$count" (That will throw an error if the inputs are not integers)



  • it only does a single 'cd', so things like cd - still work.



I would add that to my ~/.bashrc file, or source it in to my current shell.

Code Snippets

up () {
    local count=$1
    if [ -z "$count" ]; then
        cd ..
        return
    fi

    test "$count" -eq "$count" || return 1

    local todir=""
    for i in `seq 1 $count`;
    do
      todir="../$todir"
    done
    cd $todir
}

Context

StackExchange Code Review Q#108707, answer score: 22

Revisions (0)

No revisions yet.