在 BASH / SHELL 中捕获输出和退出代码
Capturing output and exit codes in BASH / SHELL
我无法在 shell.
中捕获输出和退出代码
我需要比较 2 个脚本的退出代码,如果它们不匹配,我想回显我的 2 个脚本的输出。
我目前拥有的:
#!/bin/bash
resultA=$(./a.out 2>&1)
exitA=$?
resultB=$(./b.out 2>&1)
exitB=$?
问题是未捕获可能的分段错误消息,因为它针对我当前 shell 的错误输出,但我需要捕获所有内容,包括分段错误之类的内容。
什么是解决方法,不像真实消息那样详细:
#!/bin/bash
resultA=$(./a.out 2>&1)
exitA=$?
resultB=$(./b.out 2>&1)
exitB=$?
if [ $exitA == 139 ]; then
resultA=$resultA"Segmentation Fault"
fi
这使得词段错误至少出现在我的结果变量中。
查看 hek2mgl 的回答,了解输出中缺少消息的原因。
Bash 联机帮助页提供了解决方案的提示:
When a command terminates on a fatal signal N, bash uses the value
of 128+N as the exit status.
您可以使用它来处理信号杀死您的一个子进程的特殊情况。
可以捕获段错误消息,但您确实需要努力。
这是一种方法:
outputA=$(bash -c '(./a)' 2>&1)
这里我们创建了一个child shell(with bash -c
),它的stderr被重定向到stdout,然后得到那个child来显式执行程序子shell。 subshell 中的错误将被 child bash 捕获,然后生成错误消息(与交互式 [=19= 生成的消息不完全相同) ]):
$ echo $outputA
bash: line 1: 11636 Segmentation fault (core dumped) ( ./a )
感谢@rici,这是我问题的完整解决方案:
#!/bin/bash
resultA=$(bash -c '(./a.out); exit $?' 2>&1)
exitA=$?
resultB=$(bash -c '(./b.out); exit $?' 2>&1)
exitB=$?
我无法在 shell.
中捕获输出和退出代码我需要比较 2 个脚本的退出代码,如果它们不匹配,我想回显我的 2 个脚本的输出。
我目前拥有的:
#!/bin/bash
resultA=$(./a.out 2>&1)
exitA=$?
resultB=$(./b.out 2>&1)
exitB=$?
问题是未捕获可能的分段错误消息,因为它针对我当前 shell 的错误输出,但我需要捕获所有内容,包括分段错误之类的内容。
什么是解决方法,不像真实消息那样详细:
#!/bin/bash
resultA=$(./a.out 2>&1)
exitA=$?
resultB=$(./b.out 2>&1)
exitB=$?
if [ $exitA == 139 ]; then
resultA=$resultA"Segmentation Fault"
fi
这使得词段错误至少出现在我的结果变量中。
查看 hek2mgl 的回答,了解输出中缺少消息的原因。
Bash 联机帮助页提供了解决方案的提示:
When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.
您可以使用它来处理信号杀死您的一个子进程的特殊情况。
可以捕获段错误消息,但您确实需要努力。
这是一种方法:
outputA=$(bash -c '(./a)' 2>&1)
这里我们创建了一个child shell(with bash -c
),它的stderr被重定向到stdout,然后得到那个child来显式执行程序子shell。 subshell 中的错误将被 child bash 捕获,然后生成错误消息(与交互式 [=19= 生成的消息不完全相同) ]):
$ echo $outputA
bash: line 1: 11636 Segmentation fault (core dumped) ( ./a )
感谢@rici,这是我问题的完整解决方案:
#!/bin/bash
resultA=$(bash -c '(./a.out); exit $?' 2>&1)
exitA=$?
resultB=$(bash -c '(./b.out); exit $?' 2>&1)
exitB=$?