Ubuntu – Why does the sequence matter in the execution of these bash commands

bash

There seems to be some inconsistency that I am not able to understand regarding the bash shell.

If I execute:

ls;date;time

the results of the three queries are shown in sequence.

However, on interchanging date and time position, an error message pops up.

So if I execute:

ls;time;date

the error message says: bash: syntax error near unexpected token 'date'.

Can someone explain this?

Best Answer

The time command in your pipeline is not the /usr/bin/time binary, but the bash time built-in. Compare man time with help time. The error you see is bash failing to parse time's argument. This must either be present or be a newline. It is a newline in your first example but absent in the second.

On the other hand, if you were to run

ls;date;'time'

or

ls;'time';date

where the quotes around 'time' revoke its status as a reserved word, then bash has no problems parsing the line. It now parses three commands in a list, which it will execute in sequence, and /usr/bin/time will report a usage error in either case.

Addendum

It was observed that though time ; date yields an error, time ; ; date does not. The likely explanation is that time ; is interpreted by bash as equivalent to time <newline>. The expression time ; ; date is then parsed as the list of time ; and date.

This is consistent with the observation that time ; and time ; ; are legal as well, the second being parsed as the singleton list containing time ; followed by the optional semicolon allowed after lists.

So another way of explaining why time ; date yields the error bash: syntax error near unexpected token 'date' is that time consumes the semicolon separating it from date. It can only do that because time is a bash reserved word.

Related Question