Redirect standard input dynamically in a bash script

前端 未结 7 828
忘了有多久
忘了有多久 2020-12-13 13:56

I was trying to do this to decide whether to redirect stdin to a file or not:

[ ...some condition here... ] && input=$fileName || input=\"&0\"
./         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 14:34

    If you're careful, you can use 'eval' and your first idea.

    [ ...some condition here... ] && input=$fileName || input="&1"
    eval ./myScript < $input
    

    However, you say that 'myScript' is actually a complex command invocation; if it involves arguments which might contain spaces, then you must be very careful before deciding to use 'eval'.

    Frankly, worrying about the cost of a 'cat' command is probably not worth the trouble; it is unlikely to be the bottleneck.

    Even better is to design myScript so that it works like a regular Unix filter - it reads from standard input unless it is given one or more files to work (like, say, cat or grep as examples). That design is based on long and sound experience - and is therefore worth emulating to avoid having to deal with problems such as this.

提交回复
热议问题