Reputation: 711
The command od / /dev/null
returns both standard error and standard output and is used here just for test.
I can redirect the standard error to standard output with:
echo "The command result is: $(od / /dev/null 2>&1)"
Which returns:
The command result is: od: /: read error: Is a directory
0000000
Whereas the error part is "od: /: read error: Is a directory" and the non error one is "0000000".
I need to add a reference in the output to distinguish which part is the standard error, by adding a prefix "The error is:", and get and output like:
The command result is: 0000000
The error is: od: /: read error: Is a directory
If there is no error, the string "The error is:" can still be part of the output.
Any advise how to accomplish this?
EDIT:
The answer from choroba works for the test command od / /dev/null
, but when I try to use the following ssh command (which is what I'll actually use), the standard error goes at the end of the output instead of within the START/END strings and the START string is missing:
Command: echo "START___$(ssh [email protected] 2>&1 2> >(sed 's/^/ERR: /' >&2))___END"
Output: ___END__ERR: ssh: Could not resolve hostname 1.1.1.900: Name or service not known
When I use the test command with the addition of START/END strings, I get a normal output whereas the standard output and error is within START/END strings:
Command:echo "START___$(od / /dev/null 2>&1 2> >(sed 's/^/ERR: /' >&2))___END"
Output: START___0000000
ERR: od: /: read error: Is a directory___END
Any help for this scenario?
EDIT 2
I added the ssh command in a subprocess but still have the problem. Interestingly, it works OK for telnet.
SSH:
Command: echo "START___$((ssh [email protected]) 2>&1 2> >(sed 's/^/ERR: /' >&2))___END"
Output: ___END__ERR: ssh: Could not resolve hostname 1.1.1.900: Name or service not known
Telnet:
Command: echo "START___$((telnet 1.1.1.900) 2>&1 2> >(sed 's/^/ERR: /' >&2))___END"
Output: START___ERR: telnet: could not resolve 1.1.1.900/telnet: Name or service not known___END
EDIT 3 - SOLUTION
The solution to work with ssh command is to filter control chars from the ssh response before feeding sed:
echo "START___$(ssh [email protected] 2>&1 2> >(tr -d '[:cntrl:]' | sed 's/^/ERR: /' >&2))___END"
Upvotes: 0
Views: 117
Reputation: 8406
For Debian based Linuxes, run apt install devscripts
, and then try the annotate-output
util.
annotate-output od / /dev/null
Output:
07:21:44 I: Started od / /dev/null
07:21:44 E: od: /: read error: Is a directory
07:21:44 O: 0000000
07:21:44 I: Finished with exitcode 1
Upvotes: 0
Reputation: 241858
You can use sed and the process substitution:
echo "The command result is: $(od / /dev/null 2>&1 2> >(sed 's/^/ERR: /' >&2))"
Upvotes: 1