echo "output of echo" > f1.txt what is this
As a result, f1.txt was created(it did not exist earlier), and this is the content of f1.txt
cat f1.txt
output of echo what is this
It seems that ">" can take two arguments, the first argument is the file name, and the second is the input for the file.
but when I changed echo to cat, it doesn't work
cat < a.txt > f1.txt ohlala
cat: ohlala: No such file or directory```
Please explain how this line - "echo "output of echo" > f1.txt what is this" works exactly. I can't find the > syntax for this kind.
CodePudding user response:
The output redirection doesn't have to be the last pair of words of the command; they can occur any time after the command name (and in the case of a simple command, even before the command name.
What the shell does is first scan the entire command looking for > <word>
, then processes that as an output redirection before running the command with the remaining words as the arguments. All of the following are equivalent:
echo "output of echo" > f1.txt what is this
echo "output of echo" what > f1.txt is this
echo "output of echo" what is > f1.txt this
echo "output of echo" what is this > f1.txt
echo > f1.txt "output of echo" what is this
> f1.txt echo "output of echo" what is this
because > f1.txt
is removed, leaving behind
echo "output of echo" what is this
as the command to actually execute, namely echo
with 4 arguments.
>
takes one "argument"; the shell uses it to open a file for writing and passes that file descriptor to the command (when it finally runs) to use as standard output. In other words, no command is passed to >
, but rather whatever >
produces is passed to the process that executes the command.
Your cat
command, after removing the input and output redirections, is cat ohlala
, and there is no file named ohlala
for cat
to open. (It's not a shell error, but a cat
error.)