前置命令,stdout和stderr

Sta*_*ked 4 bash shell

我有以下代码,它读取许多命令,打印它们并打印它们的输出.

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
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

我想区分stdout和stderr并使用stderr的'E:'前缀.另外我想打印每个命令行的退出代码.

我怎样才能做到这一点?

Joh*_*ica 10

#!/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
Run Code Online (Sandbox Code Playgroud)