[TUHS] sh: cmd | >file

Robert Clausecker fuz at fuz.su
Sat Jan 4 21:47:50 AEST 2020


Good morning!

On Sat, Jan 04, 2020 at 11:07:18AM +0100, markus schnalke wrote:
> One creates an empty file or truncates a file with:
> 
> 	>file
> 
> why not with:
> 
> 	:>file
> ?
> 
> To me it looks to be the more sensible ... more regular way.
> 
> IO redirections for the shell itself could be made with:
> 
> 	exec >file 5>&
> 
> no matter if ``>file'' is a simple command or not. Because of
> ``exec'' the line is valid syntax (although the grammer probably
> was retro-fitted), and the manpages (mksh, bash, heirloom sh) all
> document exec without a command as a separate case (and the code
> probably handles it as a separate case as well), thus nothing is
> gained here from making ``>file'' a simple command.
> 
> 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 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.  So when the shell sees ">file", it opens "file" for writing
in preparation of the rest of the command.  If no command comes, the
line is handled the same way as an empty one and the redirections are
discarded.  The shell could print an error here, 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 and I'd say that nobody really thought about this
being a thing when the shell was originally written.

Yours,
Robert Clausecker

-- 
()  ascii ribbon campaign - for an 8-bit clean world 
/\  - against html email  - against proprietary attachments


More information about the TUHS mailing list