在shell脚本中获取进程的返回值

Son*_*hra 2 bash shell

我有一个 C 程序,比如说hello_world。main 函数返回一个int. 我可以在 shell 脚本中访问和使用这个返回值吗?

这是C代码。我编写了一个非常简化的程序版本。实际代码是 1.2K 行。

/*hello_world.c*/
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i = 0;
    if (argc == 2) {
        i = atoi(argv[1]);
        printf("Hello World - %d\n", i);
        return 0;
    }
    else return -1;
}
Run Code Online (Sandbox Code Playgroud)

这是运行上述代码编译后生成的可执行文件的bash脚本。我正在使用 GCC 4.1.2 并使用编译gcc -o hello_world hello_world.c

#!/bin/bash
ret=hello_world 31 # this gives a `command not found` error
if [ ret -eq 0 ]; then
    echo "success"
fi
Run Code Online (Sandbox Code Playgroud)

有什么方法可以访问脚本的返回值吗?

Iha*_*imi 6

这是一件很简单的事情

hello_world 31
if [ $? -eq 0 ];
then
    echo "success"
fi
Run Code Online (Sandbox Code Playgroud)

但是如果你想捕获程序的OUTPUT

output=$(hello_world 31)
Run Code Online (Sandbox Code Playgroud)

或者

output=`hello_world 31`
Run Code Online (Sandbox Code Playgroud)

  • 通常会打印到标准输出的任何内容,因此在这种情况下,字符串“Hello World - 31\n” (2认同)