Dmytro Lysak
Dmytro Lysak

Reputation: 477

redirect error output to function in bash?

How do I redirect the error output from a command to a function?

E.g. I have:

function logit(){
    read output
    echo "error occured -- $output" >> $file
}

mkdir /tmp/pop.txt | logit

But the above doesn't work, the variable "$output" doesn't contain anything.

Upvotes: 0

Views: 647

Answers (1)

William Pursell
William Pursell

Reputation: 212248

It's not entirely clear what you mean (in a comment), but perhaps you are looking for something like:

logit(){
    printf "error occured -- ";
    cat
} >> "$file"

exec 3>&1
{
    mkdir /tmp/pop.txt 
    chown ...
    chmod ... 
} 2>&1 1>&3  | logit 

This routes the stdout of all the commands in the block to the original stdout of the script while directing the errors streams of all to the logit function. Rather than simply dumping error occurred -- as a header and ignoring newlines in the input, it might be better to implement logit as:

logit(){ sed 's/^/ERROR: /' >> "$file"; }

or maybe even add a timestamp:

logit(){ perl -ne 'printf "%s: ERROR: %s", scalar gmtime, $_'; } >> "$file"

Upvotes: 1

Related Questions