2016-07-22 382 views
-1

我有一個C程序,說hello_world。主函數返回一個int。我可以在shell腳本中訪問並使用這個返回的值嗎?在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; 
} 

這是在編譯上述代碼後運行生成的可執行文件的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 

有什麼辦法,我可以從腳本訪問返回值編譯?

+0

的bash有一個很優秀的男人-頁。你甚至試圖看看它嗎? – Olaf

+0

我儘可能在Google上搜索過。 –

+0

我做到了。不是這樣。 –

回答

4

這是一個相當簡單的事

hello_world 31 
if [ $? -eq 0 ]; 
then 
    echo "success" 
fi 

但是,如果你想捕捉的程序的輸出

output=$(hello_world 31) 

output=`hello_world 31` 
+0

「輸出」是什麼意思?返回的值? –

+2

任何通常會打印到標準輸出的東西,所以在這種情況下,字符串「Hello World - 31 \ n」 – Robert