28
$ 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?

  • 8
    They are not functionally equivalent. In the second, if open dir2 fails, open dir1 will run. That cannot be the case in the first. – D. Ben Knoble Jun 27 at 1:44
  • 2
    Related: How can I time a pipe?? – terdon Jun 28 at 14:08
70

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
| improve this answer | |
  • 5
    Good catch! The time keyword only applies to the command (compound or simple) that it precedes. So to time properly in the second command, they would need to use time open ... || time open .... – Kusalananda Jun 25 at 16:33
  • 11
    To be hideously exact, Bash's time times a pipeline, which can then contain simple or compound commands. if-then-fi is a compound command, which can be part of a pipeline, but foo && bar is a list of commands that can't be without being grouped in { } or ( ). – ilkkachu Jun 25 at 16:44
  • 1
    Try command time ... ;) – 0xC0000022L Jun 26 at 10:00
  • 1
    @pLumo, 1. OP used [[ consistently in both cases and 2. OP used it in the intended way while [ : ] basically works by accident. – Jan Hudec Jun 26 at 12:39
  • 2
    @ilkkachu, yes, the edit is good. What I mean with “by accident” is that the way it actually works is unlikely what author had in mind when they wrote it. – Jan Hudec Jun 26 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.