Redirecting the content of a file to the command "echo"

You can redirect all you want to echo but it won't do anything with it. echo doesn't read its standard input. All it does is write to standard output its arguments separated by a space character and terminated by a newline character (and with some echo implementations with some escape sequences in them expanded and/or arguments starting with - possibly treated as options).

If you want echo to display the content of a file, you have to pass that content as an argument to echo. Something like:

echo "$(cat my_file.txt)"

Note that $(...) strips the trailing newline characters from the output of that cat command, and echo adds one back.

Also note that except with zsh, you can't pass NUL characters in the arguments of a command, so that above will typically not work with binary files. yash will also remove bytes that don't form part of valid characters.

If the reason for wanting to do that is because you want echo to expand the \n, \b, \0351... escape sequences in the file (as UNIX conformant echo implementations do, but not all), then you'd rather use printf instead:

printf '%b\n' "$(cat my_file.txt)"

Contrary to echo, that one is portable and won't have problems if the content of the file starts with -.


As an alternative to $(cat file), with ksh, zsh and bash, one can also do: $(<file). That's a special operator whereby the shell as opposed to cat reads the content of the file to make up the expansion. It still strips the trailing newlines and chokes on NUL bytes except in zsh. In bash, that still forks an extra process. Also note that one difference is that you won't get any error if trying to read a file of type directory that way. Also, while $(< file) is special, $(< file; other command) is not (in zsh, when not emulating other shell, that would still expand the content of the file, by running the implicit $READNULLCMD command (typically a pager)).


Adding to other answers, you can also try input redirection instead of cat

echo $(<my_file.txt)

or

echo `<my_file.txt`

$() and `` perform the same thing, they run commands inside of their scope and give the output to the shell as if it was given as an input by the user. The only difference between these two is that $() can be recursive and `` can't be recursive.


As it was said,

If you want echo to display the content of a file, you have to pass that content as an argument to echo

For instance, you can do it like this with xargs (considering that you need to enable interpretation of backslash escapes):

$ cat my_file.txt | xargs echo -e

Or simply what you've asked (whithout interpretation of escapes sequences):

$ cat my_file.txt | xargs echo