【问题标题】:How to pass shell variable as a command line arguments in C program如何在 C 程序中将 shell 变量作为命令行参数传递
【发布时间】:2013-02-02 05:48:41
【问题描述】:

我想将 shell 变量作为命令行参数传递给 C 程序。为了实践这一点,我编写了一个基本的 C 程序,如下所示:

#include<stdio.h>  
#include<stdlib.h>
int main(int argc, char **argv){  
    int i, a, prod=1 ;
    if(argc==2)
    a = atoi(argv[1]);
    else 
    a = 8 ; 
    printf("value of cmd: %d\n",a);
    for(i=1; i <= a ; i++)
        prod *= i ;
    printf("factorial %d!= %d\n",a, prod);
}

现在通过shell脚本变量传递参数,我写了一个小脚本如下:

#!/bin/bash  
echo "Welcome to the small shell scripting!!!"
for ((i=4; i<9;i++))
do
        "../programming/ctest/arg $i"
done

其中../programming/ctest/arg是上述C程序的可执行文件。但是当我运行脚本输出是 ../programming/ctest/arg 4 no such file or directory 等等。在没有 shell 变量的情况下运行它会给出正确的输出。 请看一下,如果这个问题解决了,我会用它来进一步自动化

【问题讨论】:

    标签: c shell command


    【解决方案1】:
    "../programming/ctest/arg $i"
    

    先生,您需要删除引号

    ../programming/ctest/arg $i
    

    详细地说,在不删除引号的情况下,Bash 会将整个字符串解释为命令,而不是您想要的命令和参数。

    【讨论】:

    • @DanielFischer,我找不到你。 OP 是什么意思,在问题 15 分钟前它不能接受答案?请解释一下。我只是投了赞成票,因为答案对我有用。
    • @user976754 最好像../programming/ctest/arg "$i" 那样引用变量$i,以防参数中包含空格
    猜你喜欢
    • 2015-01-21
    • 2015-08-05
    • 2013-08-13
    • 2013-06-26
    • 2021-11-21
    • 2020-08-19
    • 2013-07-12
    • 1970-01-01
    相关资源
    最近更新 更多