raffian
raffian

Reputation: 32066

customize command response with prefix for error messages only

I'm writing a bash script that retrieves apparent disk usage for a list of folders:

du -sb /logs
du -sb /var/xyz
du -sb /usr/local/bin

If directories exists, output is:

98983493 /logs
1489872 /usr/local

...but if it doesn't, output may be:

> cannot read directory `/logs': Permission denied 
> cannot access `/usr/local': No such file or directory

I have to parse the response; can I prefix error message to make that easier? I'd rather deal with a single error identifier than varying ones; something like this...

**error** cannot read directory `/logs': Permission denied 
**error** cannot access `/usr/local': No such file or directory

Scripting is definitely my weak point, and I admit nothing has been tried aside from a quick search.

Limitations

Upvotes: 0

Views: 230

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

You can accomplish this with bash by redirecting stder into a process substitution:

(
    echo stderr >&2
    echo stdout
    echo stdout2
    echo stderr2 >&2 
) 2> >( sed 's/^/**error**/')
stdout
stdout2
**error**stderr
**error**stderr2

It appears you lose the interleaving of stdout and stderr, but you keep their relative ordering.

Upvotes: 2

Related Questions