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

Bash function to dynamically move N directories above the current directory

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

Problem


  • up moves N directories above the current directory (executes "cd ..""


N times)

  • When executed without input values it moves only one


directory above the current directory

  • When executed with input


values, up uses the first input value (checking to see if it is a
positive integer)to move above the current directory the specified
number of directories

up() {
if [ -z "$1" ]
then
eval "cd .."
else
if [ "$1" -eq "$1" ]
then
if [ "$1" -gt "0" ]
then
for i in
seq 1 $1;
do
eval "cd .."
done
eval "pwd"
else
echo "First argument is not a positive integer"
fi
else
echo "First argument is not an integer"
fi
fi
}


I did consider building a cd ../../.. etc., chain which would execute after the for loop builds the required string and would also preserve the usefulness of cd - but this version was slightly cleaner.

The [ "$1" -eq "$1" ] thing is one way to check if a value is an integer.

Solution

If you're writing this as a shell function, then you don't need to eval.

The indentation could be done more idiomatically. By using elif, you can eliminate one level of indentation and make the code structure clearer.

up() {
    if [ -z "$1" ]; then 
        cd ..
    elif [ "$1" -eq "$1" ]; then
        if [ "$1" -lt 0 ]; then
            echo "First argument is not a positive integer"
        else
            for i in `seq 1 $1`; do
                cd ..
            done
            pwd
        fi
    else
        echo "First argument is not an integer"
    fi
}


Your question is very similar to this one. The main problem, as you have already noted in your own comment, is that by doing multiple cd .. in sequence instead of one cd ../../.., you would be inserting many hops into the directory history. Then, cd - or referencing $OLDPWD wouldn't work as expected.

Code Snippets

up() {
    if [ -z "$1" ]; then 
        cd ..
    elif [ "$1" -eq "$1" ]; then
        if [ "$1" -lt 0 ]; then
            echo "First argument is not a positive integer"
        else
            for i in `seq 1 $1`; do
                cd ..
            done
            pwd
        fi
    else
        echo "First argument is not an integer"
    fi
}

Context

StackExchange Code Review Q#111949, answer score: 2

Revisions (0)

No revisions yet.