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?
Asked
Active
Viewed 2.3k times
7
Jeff Schaller
- 67,283
- 35
- 116
- 255
GypsyCosmonaut
- 4,119
2 Answers
11
Why doesn't the input redirection work with
echobut works withcat?
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)
dr_
- 29,602
7
You can use echo to read the file.txt( not to redirect ) as follows:
echo "$(<file.txt)"
Sample output :
abcdef
GAD3R
- 66,769
-
14To split hairs, echo is still not reading the file; the shell is. – Jeff Schaller May 07 '17 at 14:45
-
4@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
echowhich in turn may treat it as an option, expand sequences or choke on it if it's too large. – Stéphane Chazelas May 08 '17 at 07:35
echo < file.txt? Input redirection works just fine, it's just thatechodoesn't try to read anything fromstdin. – Satō Katsura May 07 '17 at 13:58