I have a bash application that is producing some result, and I'd like to echo the result to either stdout
or to a user chosen file. Because I also echo other interactive messages going to the screen, requiring the user to explicitly use the >
redirection when he wants to echo the result to a file is not an option (*), as those messages would also appear in the file.
Right now I have a solution, but it's ugly.
if [ -z $outfile ]
then
echo "$outbuf" # Write output buffer to the screen (stdout)
else
echo "$outbuf" > $outfile # Write output buffer to file
fi
I tried to have the variable $outfile
to be equal to stdout
, to &1
and perhaps something else but it would just write to file having that name and not actually to stdout. Is there a more elegant solution?
(*) I could cheat and use stderr
for that purpose, but I think it's also quite ugly, isn't it?
/dev/stdout
works in some case, but is not a good idea or can be problematic in some cases, then I'm better off doing the ugly if/else solution ?! – Bregalad Jan 10 '17 at 10:50[ -z "$logfile" ] || exec 3> "$logfile"
It looks like some shorthand if/then/else. Would you care to explain ? Thanks. – Bregalad Jan 10 '17 at 14:02||
is or. Either$logfile
is empty or you run theexec
command. Check your shell man page. – Stéphane Chazelas Jan 10 '17 at 14:11[ A ] || B
is just a shorthand forif [ ! A ]; then B; fi
that have absolutely nothing to do with boolean logic or, right ? – Bregalad Jan 11 '17 at 07:46A || B
is a bit likeif ! A; then B; fi
in that it executes the B command only if the A command returns false (note that you can use any command in the condition part of anif
statement, not just the[
command). It has everything to do with boolean logic. It's just that in shells, booleans are the exit status of commands (0 for true, anything else for false). The[
command exits with 0 when the test expression it evaluates resolves to true. You can doif A || B; then echo Either A or B returned true; fi
for instance (B would not be run if A returned true, like in C). – Stéphane Chazelas Jan 11 '17 at 09:39