Home > Net >  Input redirection in test1 > test2 < test3
Input redirection in test1 > test2 < test3

Time:12-10

I am trying to understand how input redirection works so that I can simulate it in a shell I am building. Let's say we create 3 files:

echo this is test 1 > test1
echo this is test 2 > test2
echo this is test 3 > test3

And then we try to redirect input and output using a command like cat test1 > test2 < test 3. The contents of test2 will become: this is a test1. I would expect them to become this is a test 3 since this is the last "operation". What am I getting wrong? Thank you in advance!

PS If you can direct me to a guide on how redirection works when having complicated commands like the one above I would be grateful!

CodePudding user response:

cat does not read from stdin when it has non-option arguments unless one of those arguments specifies stdin. In the example you provided, cat test1 > test2 < test3, the file test3 is the input stream for cat, but cat is ignoring it because you didn't specify - as an argument. If you instead do cat test1 - > test2 < test3, then cat will read its stdin, but the final content of test2 will not merely be the content of test3, but the concatenation of test1 and test3.

Perhaps you should try the experiments:

cat test1 - > test2 < test3
cat > test2 < test3
cat - test1 - > test2 < test3
cat - - test1 test1 > test2 < test3

Also, perhaps look at

< test3 cat > test2
cat < test3 - test1 > test2
  • Related