Redirect standard input dynamically in a bash script

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

    First of all stdin is file descriptor 0 (zero) rather than 1 (which is stdout).

    You can duplicate file descriptors or use filenames conditionally like this:

    [[ some_condition ]] && exec 3<"$filename" || exec 3<&0
    
    some_long_command_line <&3
    

    Note that the command shown will execute the second exec if either the condition is false or the first exec fails. If you don't want a potential failure to do that then you should use an if / else:

    if [[ some_condition ]]
    then
        exec 3<"$filename"
    else
        exec 3<&0
    fi
    

    but then subsequent redirections from file descriptor 3 will fail if the first redirection failed (after the condition was true).

提交回复
热议问题