When it comes to redirection, it is important to note that Linux commands can interpret the argument you pass to them differently, thus leading to different behaviors. The crucial part is to understand that
- Some commands expect a path to a file and put the contents of that file within their STDIN. After that, such commands read from there, process it, and produce their output. For example,
cat does so.
- Other commands put nothing within their STDIN and don't read from there. In other words, the STDIN is simply ignored. Instead, they directly read from theirs arguments and generate the output.
Therefore, some commands can depend entirely on what is within their STDIN, while others don't give a damn for what is there. That is important for redirection because if you redirect a STDOUT to the STDIN of a command that ignores it, you won't get the desired behavior.
If you run
cat
you will notice as if cat is hung, waiting for something. It happens because, if no content is passed to within the STDIN, the standard input is, by default, attached to the keyboard. In other words, cat is waiting us to type any content and send to it by pressing enter.
On the other hand,
echo
simply leaves the command because it doesn't reads from the STDIN. As it had no argument, there is nothing to the printed.
Therefore, if you type
echo < my_file.txt
Normally, echo would treat my_file.txt as an argument and would simply produce my_file.txt in the STDOUT, but < changes how my_file.txt is treated by the shell. Now, instead of passing my_file.txt as an argument to echo, the shell puts the content of ./my_file.txt within the STDIN of echo. As we saw before, it doesn't print anything because echo doesn't read from the standard input.
If you really want that echo reads from STDIN, you must use xargs, that is,
xargs echo < my_file.txt
< makes my_file.txt not an argument, but a path to a file whose content is put within STDIN.
xargs runs the command given to it (echo) with the arguments read from STDIN.
Now it will prints out "Hello".
Similarly,
cat my_file.txt | xargs echo
also works:
cat get the content of ./my_file.txt and put it within its STDIN and print this content in its STDOUT.
- The pipe
| takes the STDOUT of cat and put it within the STDIN of echo instead of printing this STDOUT on the terminal (the default behavior).
xargs runs the command given to it (echo) with the arguments read from STDIN.
echo?\n,b...) in the file, which would be a valid usage ofecho(at least a standardecho). Or presumably he wants to understand why it doesn't work that way. In any case, no reason to downvote IMO.echoandprintfdon't handlestdin, unfortunately, that's why I'm looking, but I've got some text output from a command chain with embedded"\n"characters and I'd like to just print it properly. Is it so hard to imagine a use case where someone wants to print text to console?