2

This question already has an answer here:

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?

marked as duplicate by Stéphane Chazelas, Jeff Schaller, Community May 8 '17 at 10:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 6
    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. – Satō Katsura May 7 '17 at 13:58
  • @SatoKatsura Sorry, didn't know, thanks for help.. – GypsyCosmonaut May 7 '17 at 14:19
5

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

echo "$(<file.txt)"

Sample output :

abcdef
  • 8
    To split hairs, echo is still not reading the file; the shell is. – Jeff Schaller May 7 '17 at 14:45
  • 3
    @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. – Stéphane Chazelas May 8 '17 at 7:35
6

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.