5

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
$
sh.3.ll
  • 301
  • 2
  • 10

1 Answers1

11

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.

muru
  • 69,900
  • 13
  • 192
  • 292
  • 3
    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 '19 at 13:34
  • 2
    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 '19 at 13:34
  • So basically, whenever a file is passed for reading, cat will always ignore the STDIN? – sh.3.ll Oct 23 '19 at 13:56
  • 1
    @sh.3.ll: unless `-` is used. – jesse_b Oct 23 '19 at 14:12