Difference between 'cat < file.txt' and 'echo < file.txt'

17,938

Solution 1

You can use echo to read the file.txt( not to redirect ) as follows:

echo "$(<file.txt)"

Sample output :

abcdef

Solution 2

Why doesn't the input redirection work with echo but works with cat?

Because the echo command doesn't accept anything from stdin like cat does, it accepts only parameters.

From man cat:

cat - concatenate files and print on the standard output

Synopsis

cat [OPTION]... [FILE]...

Description

Concatenate FILE(s), or standard input, to standard output.

From man echo:

echo - display a line of text

Synopsis

echo [SHORT-OPTION]... [STRING]...

echo LONG-OPTION

Description

Echo the STRING(s) to standard output.

(emphasis mine)

Share:
17,938

Related videos on Youtube

GypsyCosmonaut
Author by

GypsyCosmonaut

Updated on September 18, 2022

Comments

  • GypsyCosmonaut
    GypsyCosmonaut almost 2 years

    I have a file named file.txt which has some content say 'abcdef', when I do cat < file.txt I get the output abcdef but when I do echo < file.txt, no output is returned. Why doesn't the input redirection work with echo but works with cat?

    • Satō Katsura
      Satō Katsura about 7 years
      What output did you expect from echo < file.txt? Input redirection works just fine, it's just that echo doesn't try to read anything from stdin.
    • GypsyCosmonaut
      GypsyCosmonaut about 7 years
      @SatoKatsura Sorry, didn't know, thanks for help..
  • Jeff Schaller
    Jeff Schaller about 7 years
    To split hairs, echo is still not reading the file; the shell is.
  • Stéphane Chazelas
    Stéphane Chazelas about 7 years
    @Jeff, technically, the shell is reading the file, stripping the trailing newline characters (potentially choking on NUL bytes and invalid characters depending on the implementation) and passing that as an argument to echo which in turn may treat it as an option, expand sequences or choke on it if it's too large.