I'd like my script to output to stdout unless it gets a filename as an argument. An obvious way is like so:
if [ -e "$1" ]; then
command_with_output >$1
else
command_with_output
fi
It's pretty ugly and has repetition, so I'd like a more consice way to do it.
I tried the following, but it doesn't work.
[ -e "$1" ] && outfile=$1 || outfile='&1'
command_with_output >$outfile
Edit:
This doesn't change the relevancy of the answers, but I realized after I made the question that touch "$1" && outfile=$1 is really what I need instead of [ -e "$1" ] && outfile=$1 since the file may not already exist, and I want to make sure I can write to it or create it, not just that it exists. I'm not changing the question because it would put the answers out of sync.

./yourscript.sh filenameinstead of./yourscript.sh > filename? I'd say no, or at least the marginal benefit is normally outweighed by the additional complexity in the interface. The exception to the rule is programs with non-human-readable output (Say, image converter, or wget). Those usually provide an-o filenameswitch where filename can be-to say you really want that crap on stdout. – Jo So Jul 2 '12 at 18:39