[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Cat File Truncation Question - Unsure of How To Post To Discussion L
From: |
Bernhard Voelker |
Subject: |
Re: Cat File Truncation Question - Unsure of How To Post To Discussion List |
Date: |
Sat, 30 Mar 2019 17:59:05 +0100 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.5.2 |
On 3/27/19 8:01 PM, Sean Lum wrote:
> On Wed, Mar 27, 2019 at 11:48 AM Sean Lum <address@hidden> wrote:
>
>> Hi,
>>
>> My name is Sean Lum. I've run into something on my Linux systems (Debian,
>> Fedora, and Arch, occurring both in bash and sh on all three, and all the
>> machines are up to date at the time of testing), and it involves shell
>> input/output redirects and the cat command. I am not completely sure on how
>> the cat command handles shell redirects, but similar behavior is also
>> present in the less command. I am unsure if this is a bash command or cat
>> command issue or a less command issue.
cat does not do the '>' redirection but the shell does. Therefore, you will
observe this behavior with all programs, even with some which do not write
to stdout.
>> The issue is as such, when the input file is the output file, in a
>> truncating redirect, the file is truncated, and no content written to the
>> file by the redirect. This behavior is the same on the less command, using
>> the ">" operator, but has differing behavior on the ">>" operator.
>>
>> $ echo "hi" > file.txt
>> $ cat file.txt
>> hi
>> $ cat file.txt > file.txt
>> $ cat file.txt
>> <no output>
The point is that the shell begins with the (truncating) redirection
even before the program - in this case cat(1) - is run.
As a result, cat sees an empty file.txt, and therefore
does not write anything to stdout, i.e., the redirection
remains empty.
This all works as it should.
> $ echo $(cat file.txt) > file.txt
> $ cat file.txt
> hi
>
> And that seems to be it.
The case here is that the shell runs "cat file" first, and therefore
the echo command in the second step will be called with the output of
cat. The output of echo is redirected to file.txt.
Nevertheless, I would really avoid such a construct, as some shells
might implement the $(...) syntax differently, which could lead to the
same empty result as above.
Finally, such shell code is hard to read, as the user unnecessarily
has to think about in what order the $() call and the '>' redirection
is implemented.
After all, this is not a bug in cat.
Does this answer your question?
Have a nice day,
Berny