1

According to bash manual:

The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

but I fail to see why. Let's try to take a closer look at what $(< file) means and what it does:

  1. by definition, a $(command) construct expands to whatever command writes to stdout.
  2. in our case, command is < file, so it consists solely of a stdin redirection to file. Does it write anything to stdout? My guess would be it doesn't (why would a stdin redirection alone affect stdout?), but apparently it does since $(command) expands to contents of file instead of nothing.

Basically, I fail to see the "obvious" equivalence of $(cat file) and $(< file). How does it follow from bash syntax? Is there a special rule explaining why stdin is copied to stdout in this particular case (or, generally, what happens to streams for empty commands, i.e. commands consisting solely of one or more redirections)? Is it a "bashism" or does the same equivalence hold true for other shells (especially dash) as well?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Peter
  • 313
  • 1
  • 3
  • 10
  • 1
    It just evaluates to a descriptor that's open on that file for reading, instead of a descriptor that is the read end of a pipe hooked up to the standard output of a command. – Shawn Apr 05 '20 at 17:23
  • 1
    What do you mean *Why*? It's a feature, a special case in command substitution. I agree that it doesn't make much sense but some shells (bash, zsh, mksh) have it. – oguz ismail Apr 05 '20 at 17:54
  • @oguz I think OP's asking since `< file` isn't the same as `cat file`, outside of command substitution. I certainly am. – wjandrea Apr 05 '20 at 18:10
  • 1
    @oguz By "why" I meant: does this feature follow directly from syntactic/semantic rules or is it just a special case? Is this behaviour documented anywhere in more detail or is the short excerpt from bash manual I quoted ("The command substitution $(cat file) can be replaced by the equivalent but faster $(< file)") all there is to it? – Peter Apr 05 '20 at 18:11
  • 2
    `does this feature follow directly` no `is it special case` yes `Is this behaviour documented` no – KamilCuk Apr 05 '20 at 18:13
  • FWIW it's not mentioned in the manual under [Redirecting Input](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/html_node/Redirections.html#Redirecting-Input). Also I just tried it in Dash and it didn't work. – wjandrea Apr 05 '20 at 18:13
  • 1
    It's not very different from `> file` which will quickly empty/truncate a file. – Mark Setchell Apr 05 '20 at 18:22
  • 1
    I second what KamilCuk said above, except that the part you quoted **is** the documentation, what else do you expect? – oguz ismail Apr 05 '20 at 18:33
  • 1
    Oh, and if you're interested, here is [a long and boring discussion about this on comp.unix.shell](https://groups.google.com/forum/#!topic/comp.unix.shell/nRAhNPDZ9EI) (the other one was broken). – oguz ismail Apr 05 '20 at 18:50

0 Answers0