Tag: bash

Only pipe STDERR output in `bash` with timestamp

Only pipe STDERR output in bash with timestamp

bash

In order to discard standard output and only log the standard error, following command can be used. The second part of command is to prefix the current timestamp in the output

sh monitor 2>&1>/dev/null | ts '[%Y-%m-%d %H:%M:%S]'

dash

If need to run in dash, such as running in crontab, above syntax is wrong, use following command instead

sh monitor 3>&1 1>/dev/null 2>&3 3>&- | ts '[%Y-%m-%d %H:%M:%S]'

Note: This command can be run in bash too

References

Prepending a timestamp to each line of output from a command
Pipe only STDERR through a filter

Apply filter to STDERR in Linux

Apply filter to STDERR in Linux

STDOUT ────────────────┐
                       ├─────> terminal/file/whatever
STDERR ── [ filter ] ──┘

Method

If ./a.out outputs as below

In STDERR:

stderr output

In STDOUT:

more regular

Then the following command will output as below.

# ./a.out 3>&1 1>&2 2>&3 3>&- | sed 's/e/E/g'
more regular
stdErr output

Explanation

    First save stdout as &3 (&1 is duped into 3)
    Next send stdout to stderr (&2 is duped into 1)
    Send stderr to &3 (stdout) (&3 is duped into 2)
    close &3 (&- is duped into 3)

References

Pipe only STDERR through a filter