0

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.

4
  • You have to redirect stderr(2) to stdout(1) to make it work like this: mkdir /tmp/pop.txt 2>&1 | logit Commented Oct 3, 2022 at 15:29
  • 1
    or shorter form : mkdir /tmp/pop.txt |& logit Commented Oct 3, 2022 at 15:31
  • And consider using -p option for mkdir. Commented Oct 3, 2022 at 15:31
  • It works, but now I have another issue, I have other commands following mkdir, like chown, and even though they don't trigger any errors, they still trigger the "logit" function. Is there a way to trigger the command upon receiving stderr? Commented Oct 3, 2022 at 15:42

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

ah, interesting, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.