Redirect standard input dynamically in a bash script

前端 未结 7 827
忘了有多久
忘了有多久 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:40

    Use eval:

    #! /bin/bash
    
    [ $# -gt 0 ] && input="'"$1"'" || input="&1"
    
    eval "./myScript <$input"
    

    This simple stand-in for myScript

    #! /usr/bin/perl -lp
    $_ = reverse
    

    produces the following output:

    $ ./myDemux myScript
    pl- lrep/nib/rsu/ !#
    esrever = _$
    
    $ ./myDemux
    foo
    oof
    bar
    rab
    baz
    zab
    

    Note that it handles spaces in inputs too:

    $ ./myDemux foo\ bar
    eman eht ni ecaps a htiw elif
    

    To pipe input down to myScript, use process substitution:

    $ ./myDemux <(md5sum /etc/issue)
    eussi/cte/  01672098e5a1807213d5ba16e00a7ad0
    

    Note that if you try to pipe the output directly, as in

    $ md5sum /etc/issue | ./myDemux
    

    it will hang waiting on input from the terminal, whereas ephemient's answer does not have this shortcoming.

    A slight change produces the desired behavior:

    #! /bin/bash
    
    [ $# -gt 0 ] && input="'"$1"'" || input=/dev/stdin
    eval "./myScript <$input"
    

提交回复
热议问题