On 1/4/20 6:47 AM, Robert Clausecker wrote:
> This is what wonder about: Why make
``>file'' a simple command,
> when -- as far as I can currently see -- there is no reason to do
> so, as all uses could have been achieved in more regular ways as
> well?
I'm going to answer in terms of the Bourne shell and its successors.
I think the key reason is that the shell does not
build an AST from
the command you type, instead executing the phrases it encounters as it
sees them.
This is false.
So when the shell sees ">file", it opens
"file" for writing
in preparation of the rest of the command.
Also not correct, at least if you mean opening it before completing the
parse.
If no command comes, the
line is handled the same way as an empty one and the redirections are
discarded.
Not really. The shell parses the line into a list of words. Those words
make up a simple command, since none of the words were identified as a
reserved word, and so are not the first word of a compound command. It's
the default case, basically.
The POSIX standard gives a pretty good summary of what happens next:
the redirections get separated out and the rest of the words are
expanded.
You already have to deal with the expansions returning nothing, since the
words could all be null variable expansions, so the case where there are
no words besides redirections and assignment statements isn't that much
different.
The shell could print an error here,
It could, but Bourne chose not to.
but avoiding the side
effect of opening "file" for lines just consisting of redirects would be
difficult. But then, why should it print an error? The behaviour is
not harmful after all
This is true. There aren't any other cases where the shell makes a null
expansion an error without being directly asked, so it would not have
made sense to make a command consisting entirely of words that expand to
null an error. There's no good reason to treat a null command differently
from that case.
and I'd say that nobody really thought about
this
being a thing when the shell was originally written.
On the contrary, I think Bourne made a conscious choice to handle
redirections `separately' from simple command expansion and execution, and
a conscious choice to continue to process redirections (in a subshell, as
if the shell had forked to execute a non-builtin) when word expansion
resulted in no words.
It's the `exec' case with redirections that I think was the special case,
since Bourne's (v7) shell didn't allow redirections with builtins at all.
Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU chet(a)case.edu
http://tiswww.cwru.edu/~chet/