bash – 前置命令,stdout和stderr
发布时间:2020-12-15 22:19:01 所属栏目:安全 来源:网络整理
导读:我有以下代码,它读取许多命令,打印它们并打印它们的输出. while read line ; do echo "C:$line" echo "O:$(${line} 21 | perl -pe 's,n,n,'g)n"done EOFg++-4.8 -O2 -Wall -Wextra -pedantic -pthread main.cpp./a.outEOF 输出: C:g++-4.8 -O2 -Wall -W
我有以下代码,它读取许多命令,打印它们并打印它们的输出.
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 输出: 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 ^nn 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: ========nn 我想区分stdout和stderr并使用stderr的’E:’前缀.另外我想打印每个命令行的退出代码. 我怎样才能做到这一点? 解决方法#!/bin/bash # Add a prefix to each line of stdin. prefix() { local line while read line; do printf '%s%sn' "$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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |