Bash – These two Bash lines are functionally equivalent. Can someone explain why one is faster

bashtesttime

$ time if [[ $dir2 -ot $dir1 ]] ; then open $dir2 ; else open $dir1 ; fi
real    0m0.055s
user    0m0.023s
sys     0m0.018s

$ time  [[ $dir2 -ot $dir1 ]] && open $dir2 || open $dir1
real    0m0.000s
user    0m0.000s
sys     0m0.000s

At above, I compared two methods for testing which directory is older and then opening the older directory. I guess I'm just confused why the && and || operators right after a test has the same functionality of an if/then test, and why it's faster. Are there advantages/disadvantages to each?

Best Answer

time always times the directly following pipeline.

A pipeline is a sequence of one or more commands (simple or compound) separated by one of the control operators | or |&.

if ... fi is a single compound command, and [[ ... ]] is one command. The part after && is not measured by time because foo && bar is a list of commands.

Compare:

$ time if true; then sleep 1; fi

real    0m1.004s
user    0m0.000s
sys     0m0.000s


$ time true && sleep 1

real    0m0.000s
user    0m0.000s
sys     0m0.000s

# example of pipeline separated with |:
$ time true | sleep 1

real    0m1.004s
user    0m0.000s
sys     0m0.000s

To measure time from all of the second commands, you can group them by putting it in (curly) brackets:

$ time { true && sleep 1; }

real    0m1.003s
user    0m0.000s
sys     0m0.000s
Related Question