Redirect standard input dynamically in a bash script Redirect standard input dynamically in a bash script shell shell

Redirect standard input dynamically in a bash script


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<&0some_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<&0fi

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


Standard input can also be represented by the special device file /dev/stdin, so using that as a filename will work.

file="/dev/stdin"./myscript < "$file"


(    if [ ...some condition here... ]; then        exec <$fileName    fi    exec ./myscript)

In a subshell, conditionally redirect stdin and exec the script.