Redirect standard input dynamically in a bash script

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

    How about

    function runfrom {
        local input="$1"
        shift
        case "$input" in
            -) "$@" ;;
            *) "$@" < "$input" ;;
        esac
    }
    

    I've used the minus sign to denote standard input because that's traditional for many Unix programs.

    Now you write

    [ ... condition ... ] && input="$fileName" || input="-"
    runfrom "$input" my-complicated-command with many arguments
    

    I find these functions/commands which take commands as arguments (like xargs(1)) can be very useful, and they compose well.

    0 讨论(0)
提交回复
热议问题