Linux command ambiguous redirect

后端 未结 3 989
再見小時候
再見小時候 2021-01-26 09:58

Hi I have a lab header called header.txt and I want to cat into my 3 C files cat ../header.txt > find -name *.c

What is wrong with the above statement?

3条回答
  •  轮回少年
    2021-01-26 10:25

    The I/O redirection operators <, >, etc. all only take one word as their argument, and use that as a filename. Anything else is considered part of the command line.

    So when you run this:

    cat ../header.txt > find -name *.c
    

    It's exactly the same as this:

    cat ../header.txt -name *.c > find
    

    That's probably not going to do anything useful.

    Another problem: your *.c isn't escaped or quoted, so bash will expand it rather than passing it to find.


    You can do what you seem to want with tee, which accepts any number of arguments:

    cat ../header.txt | tee *.c
    

    And then you don't even need cat any more, really.

    tee *.c < ../header.txt
    

    Of course, you could just as well do this with cp. Perhaps you meant to append to these files? If so, pass -a to tee as well.


    Interesting trivia: zsh and some other shells will let you have multiple > operators, which works just like tee. (Multiple < is also allowed and works like cat.)

    cat infile > outfile1 > outfile2
    

    But you have to actually list every file individually, so you can't use this shortcut with a glob like *.c.

提交回复
热议问题