I was trying to do this to decide whether to redirect stdin to a file or not:
[ ...some condition here... ] && input=$fileName || input="&0"
./myScript < $input
But that doesn’t work because when the variable $input is “&0”, bash interprets it as a filename.
However, I could just do:
if [ ...condition... ];then
./myScript <$fileName
else
./myScript
The problem is that ./myScript is actually a long command line that I don’t want to duplicate, nor do I want to create a function for it because it’s not that long either (it’s not worth it).
Then it occurred to me to do this:
[ ...condition... ] && input=$fileName || input= #empty
cat $input | ./myScript
But that requires to run one more command and a pipe (i.e. a subshell).
Is there another way that’s simpler and more efficient?
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:
Note that the command shown will execute the second
execif either the condition is false or the firstexecfails. If you don’t want a potential failure to do that then you should use anif/else:but then subsequent redirections from file descriptor 3 will fail if the first redirection failed (after the condition was true).