当前位置: 动力学知识库 > 问答 > 编程问答 >

Capturing output and exit codes in BASH / SHELL

问题描述:

I am having trouble capturing output and exit codes inside a shell.

I need to compare exit codes from 2 scripts and if they don't match I want to echo the output of my 2 scripts.

What I currently have:

#!/bin/bash

resultA=$(./a.out 2>&1)

exitA=$?

resultB=$(./b.out 2>&1)

exitB=$?

Problem is a possible Segmentation Fault message is not captured, because it is directed to the error output of my current shell, but I need to capture everything including something like Segmentation Faults.

What is kind of a workaround and not as detailed as the real message:

#!/bin/bash

resultA=$(./a.out 2>&1)

exitA=$?

resultB=$(./b.out 2>&1)

exitB=$?

if [ $exitA == 139 ]; then

resultA=$resultA"Segmentation Fault"

fi

This makes the words segmentation fault at least appear in my result variables.

网友答案:

It's possible to capture the segfault error message, but you really need to work at it.

Here's one way:

outputA=$(bash -c '(./a)' 2>&1)

Here we create an child shell (with bash -c) whose stderr is redirected to stdout, and then get that child to execute the program in an explicit subshell. Errors inside the subshell will be captured by the child bash, which will then generate an error message (which is not quite the same as the message produced by an interactive bash):

$ echo $outputA
bash: line 1: 11636 Segmentation fault (core dumped) ( ./a )
网友答案:

Check out hek2mgl's answer for the reason for the missing message in your output.

The Bash manpage provides a hint towards a solution:

When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.

You could use this to handle the special case of a signal killing one of your child processes.

网友答案:

Thanks to @rici this is the complete solution to my problem:

#!/bin/bash

resultA=$(bash -c '(./a.out); exit $?' 2>&1)
exitA=$?
resultB=$(bash -c '(./b.out); exit $?' 2>&1)
exitB=$?
分享给朋友:
您可能感兴趣的文章:
随机阅读: