如何将printf输出从应用程序重定向到执行应用程序的脚本?

时间:2013-09-04 12:06:35

标签: c shell

当我在shell脚本中调用外部应用程序时,我该怎么做

在可执行应用程序(a.out)中获取printf的输出并在shell提示符下打印它们吗?

脚本:

STATUS_CMD="AGQMI stop $PDH $CID"

`$STATUS_CMD` 

clear_state

echo done

AGQMI是我的应用程序,它有成功和失败案例的printf,我需要在shell输出中看到它们,但我无法查看我何时运行脚本。

输出:

Clearing state...

done

2 个答案:

答案 0 :(得分:0)

脚本的标准输出由您从脚本运行的程序继承。您可以重定向单个程序,或将其输出捕获到变量中。

#!/bin/sh
one_output=$(one -foo "bar" -baz <quux)
echo "the output from 'one' was '$one_output'"
two -pounds "$1" >two_out
echo "the output from 'two' is in the file 'two_out'"
cat two_out
echo "here is the output from 'three'"
three

答案 1 :(得分:0)

查看此recent thread。它的一个示例显示了如何在运行时编译C代码。

在这里转发摘要,基本上概念是这样的。您还可以添加更多标志或其他增强功能,如编译检查。

#!/bin/sh

OUTPUT_BINARY=/tmp/some_binary_name

# Compile the code.

gcc -o "$OUTPUT_BINARY" -xc - <<EOF
#include <stdio.h>

int main(int argc, char** argv)
{
    printf("Hello world.\n");
    return 0;
}
EOF

# Run the code.

"$OUTPUT_BINARY"

# Delete it.

rm -f "$OUTPUT_BINARY"

甚至可能有一些方法不使用文件系统文件,只是空格或管道,但基本上就是这样。