Reputation: 35233
cat concatenates files or stdin and redirects it to stdout.
$ cat file1 > file5 file2 file3 file4
concatenates file1, file2, file3 and file 4 and writes it to file5.
$ cat file1 > file5 < file2 file3 file4
concatenates file1, file3 and file4 (not file2) and writes to file5
Please explain these outputs
Examples of what happens:
~/test$ echo "this is file 1"> file1
~/test$ echo "this is file 2"> file2
~/test$ echo "this is file 3"> file3
~/test$ echo "this is file 4">file4
~/test$ cat file1 > file5 file2 file3 file4
~/test$ cat file5
this is file 1
this is file 2
this is file 3
this is file 4
~/test$ cat file1 > file5 < file2 file3 file4
~/test$ cat file5
this is file 1
this is file 3
this is file 4
Upvotes: 0
Views: 3937
Reputation: 11162
This is less about how cat
works, and more about shell redirection. The shell processes the command line before it runs the program. It's easier to see if you push all the io redirection to the end of the command. The first becomes:
cat file1 file2 file3 file4 > file5
The shell then changes the output of cat from the terminal to file5. This is completely independent of cat.
The second command is then
cat file1 file3 file4 >file5 <file2
This this changes the standard input from the keyboard to file2
and the output, like before, to file5. In this instance, because there are files specified on the command line, cat ignores the standard input, reading only from the 1, 3, and 4. The -
argument tells cat to read from standard input, so
cat file1 - file3 file4 >file5 < file2
Would output the contents of files 1-4 to file 5.
Upvotes: 2
Reputation: 30813
Redirections can be placed anywhere in the command line, although the usual way is at the end.
Your second statement is incorrect. file2 should be is ignored. (was corrected later)
Upvotes: 1
Reputation: 19989
Try to create simple bash file
#!/bin/bash
echo $@
And run
./bash.sh file1 file2 file3 file4 > file5
gives you
file1 file2 file3 file4
./bash.sh file1 file3 file4 >file5 <file2
gives you
file1 file3 file4
in file 5 you see list of arguments, what cat do is that takes list of arguments and write it to the std output, that's why file 2 is ignored, it's not a parameter, it's an input in fact
if you want cat to read from std input assign - after the command
cat file1 > file5 < file2 file3 file4 -
This will write
1111
3333
4444
2222
to the file5
< means redirection of std input, if you write
cat file1 > file5 file3 file4 -
it reads from file1, file3, and file4 and your keyboard to the file5
Upvotes: 1
Reputation: 798566
Only one redirection takes place in the shell; the rest are passed as arguments.
The first command is
cat file1 file2 file3 file4 > file5
The second command is
cat file1 file3 file4 > file5 < file2
The second command doesn't include file2
because cat
was never told to read from stdin with -
.
Upvotes: 1