Wednesday, October 22, 2014

bash: redirect stdout and stderr for a block of "code"

(I was hesitant to call "code" a bash script, as it's mostly molasses of un-refactorable hieroglyphs)

vi redirtest.sh

{
plutti
plitti
} > plutti.log 2>&1

{
pippi
} > pippi.log 2>&1


{
echo ciao
} > ciao.txt

{
echo miao
} > miao.txt



The command "plutti" and "plitti" don't exist, so I will have an error "./redirtest.sh: line 2: plutti: command not found ./redirtest.sh: line 2: plitti: command not found".
But only that block will be redirected to plutti.log.
Same story for pippi.log: you have 2 separate error logs for the 2 blocks of code.
So, not necessarily redirection has to be at the whole script level, or at the single statement level.... one can group several statements in a "try/catch" block, which is cool...IMHO at least, it gives more flexibility ...

No comments: