cat and pipe vs. redirection

9,385

In general, foo < bar and < bar foo are equivalent in bash scripting. Any time < filename is processed by the shell, it means that the command it's associated with will have its standard input come from that file. No extra command or process is involved with this; the shell does it itself.

Running cat filename reads the contents of the specified file and writes them to standard output. | between two commands means connect standard output of the left command to standard input of the right command.

Thus, both of your commands have the same effect of sending the contents of /proc/uptime to awk, but the first way starts an extra cat process to do so.

Share:
9,385

Related videos on Youtube

readytotaste
Author by

readytotaste

Updated on September 18, 2022

Comments

  • readytotaste
    readytotaste almost 2 years

    What's the difference between these two commands?

    cat /proc/uptime | awk '{print $1}'

    < /proc/uptime awk '{print $1}'

    Specifically, how does the second command work? Doesn't the redirection operator < has to be accompanied by a command? What does it mean to redirect the contents of a file like that?

    • readytotaste
      readytotaste almost 6 years
      I came across it online and wanted to know how it worked.. there was no explanation backing the usage.
    • readytotaste
      readytotaste almost 6 years
    • Joseph Sible-Reinstate Monica
      Joseph Sible-Reinstate Monica almost 6 years
      @Goro I don't see anything wrong with the second command. What's wrong about it?
    • readytotaste
      readytotaste almost 6 years
      @JosephSible can you please explain how it works?
    • Jeff Schaller
      Jeff Schaller almost 6 years
      Reading this comment from Stéphane made me smarter; thought I’d include it here.
  • Anthony Sottile
    Anthony Sottile almost 6 years
    (warning: snark): see also UUOC