Skip to content
Advertisement

which is better? using cd and execute or using absolute path?

Suppose I would like to do some operation like touch/rmetc on a specific directory in shell script. Firstly, I can do cd to that directory and do it. Secondly, I can use absolute path to do that.

My question is which one will be better in performance perspective? Which one is faster?

Advertisement

Answer

You can time it yourself:

function timeThis {
    n=0 
    path="test/a"
    rm $path
    if [[ "$1" == abs ]]; then
        path="$(pwd)/$path"
    fi  
    echo "$path"
    while [[ $n -lt 10000 ]]; do
        touch $path
        let n++ 
    done
}

echo "absolute"
time timeThis abs 
echo "relative"
time timeThis rel 

with this I get:

absolute

real    0m5.502s
user    0m3.394s
sys 0m2.398s

relative    
real    0m5.492s
user    0m3.599s
sys 0m2.373s

so it is almost the same for this many iterations on the path I tried

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement