4

When I use the command cat <<< Hey > text.txt text.txt I expect it to write "Hey" in the file text.txt and then display the file. But there is no output. How is bash interpreting it actually?

Command and its output:

$ cat <<< Hey > text.txt text.txt
$ cat text.txt
$
  • Please don't post images of text. Copy and paste the text itself into your question and format it as code by selecting it and pressing Ctrl-K or by using the ed itor's {} icon. – cas Oct 24 at 3:19
10

Maybe it will make sense if you rearrange the redirections a bit:

<<< Hey > text.txt cat text.txt

Hey is sent to stdin of cat, as a herestring. text.txt is opened for writing, and truncated. So if any text were in it, it would be gone.

cat is executed with the argument text.txt. Since a file was provided as an argument, it ignores stdin, so the Hey is unused. text.txt was truncated, so when cat runs through text.txt the argument, there's nothing to output, so text.txt, which is the stdout of cat via redirection, continues to remain empty.

  • 2
    And the “obvious” fix, <<< Hey > text.txt cat - text.txt, doesn’t work at least with GNU cat because it refuses to process an input file which is also its output file. – Stephen Kitt Oct 23 at 13:34
  • 1
    Might be worth mentioning that - can be used to tell cat to still read from stdin after reading a file but it still wouldn't work in this case since OP wants to read from the same file they are attempting to write to. – Jesse_b Oct 23 at 13:34
  • So basically, whenever a file is passed for reading, cat will always ignore the STDIN? – sh.3.ll Oct 23 at 13:56
  • 1
    @sh.3.ll: unless - is used. – Jesse_b Oct 23 at 14:12

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.