Redirect standard input dynamically in a bash script

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"

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).


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

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