Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend command, stdout and stderr

Tags:

bash

shell

I have the following code which reads a number of commands, prints them and prints their output.

while read line ; do
  echo "C:$line"
  echo "O:$(${line} 2>&1 | perl -pe 's,\n,\\n,'g)\n"
done << EOF
g++-4.8 -O2 -Wall -Wextra -pedantic -pthread main.cpp
./a.out
EOF

Output:

C:g++-4.8 -O2 -Wall -Wextra -pedantic -pthread main.cpp
O:main.cpp: In function ‘int main(int, char**)’:\nmain.cpp:3:9: warning: unused variable ‘unused’ [-Wunused-variable]\n     int unused;\n         ^\n\n
C:./a.out
O:*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x00007fff3bd01a5c ***\n======= Backtrace: =========\n/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7f6960e1ab96]\n./a.out[0x400502]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7f6960dbd76d]\n./a.out[0x400535]\n======= Memory map: ========\n\n

I would like to distinguish between stdout and stderr and use the 'E:' prefix for stderr. Also I would like to print the exit code of each command line.

How can I achieve this?

like image 840
StackedCrooked Avatar asked Dec 21 '22 00:12

StackedCrooked


1 Answers

#!/bin/bash

# Add a prefix to each line of stdin.
prefix() {
    local line
    while read line; do printf '%s%s\n' "$1" "$line"; done
}

# Execute each command. Notice the `(' and `)' surrounding the loop body, which starts
# a sub-shell for each iteration. Running in a sub-shell lets us use `trap EXIT' to
# cleanup.
while read command; do (
    # Create FIFOs for the command's stdout and stderr.
    stdout=$(mktemp -u)
    stderr=$(mktemp -u)
    mkfifo "$stdout" "$stderr"

    # Delete the FIFOs when this iteration of the loop finishes. Use `trap' to ensure
    # cleanup happens whether we finish normally or are signalled.
    trap 'rm -f "$stdout" "$stderr"' EXIT

    # Read from the FIFOs in the background, adding the desired prefixes.
    prefix 'O:' < "$stdout" >&1 &
    prefix 'E:' < "$stderr" >&2 &

    # Now execute the command, sending its stdout and stderr to the FIFOs.
    echo "C:$command"
    eval "$command" 1> "$stdout" 2> "$stderr"
    exitcode=$?

    # Wait for the `prefix' processes to finish, then print the exit code.
    wait
    echo "R:$exitcode"
    exit $exitcode
) done
like image 174
John Kugelman Avatar answered Jan 08 '23 12:01

John Kugelman