Difference between 'cat < file.txt' and 'echo < file.txt'
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 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)
Related videos on Youtube
![GypsyCosmonaut](https://i.stack.imgur.com/dvwQi.jpg?s=256&g=1)
GypsyCosmonaut
Updated on September 18, 2022Comments
-
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 doecho < file.txt
, no output is returned. Why doesn't the input redirection work with echo but works with cat?-
Satō Katsura about 7 yearsWhat output did you expect from
echo < file.txt
? Input redirection works just fine, it's just thatecho
doesn't try to read anything fromstdin
. -
GypsyCosmonaut about 7 years@SatoKatsura Sorry, didn't know, thanks for help..
-
-
Jeff Schaller about 7 yearsTo split hairs, echo is still not reading the file; the shell is.
-
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.