1

I want to pass shell variable as command line arguments to C program. To practice this I have written a basic C program which is as follows:

#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);
}

Now to pass the argument through shell script variable, I have written a small script which is as follows:

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

Where ../programming/ctest/arg is the executable file for the above C program. But when I run the script output is ../programming/ctest/arg 4 no such file or directory and so on. while running without shell variable It gives the proper output. Kindly look at that, if this issue is solved I will use it for further automation

1 Answer 1

2
"../programming/ctest/arg $i"

You need to remove quotes good sir

../programming/ctest/arg $i

To elaborate, without removing the quotes Bash will interpret the entire string as a command, instead of a command and argument like you intended.

Sign up to request clarification or add additional context in comments.

2 Comments

@DanielFischer, I could not get you. What do you mean by OP and it can't accept answer before the question is 15 minutes old? Kindly explain it. I just upvoted because the answer was useful for me.
@user976754 It is even better if you quote the variable $i as in ../programming/ctest/arg "$i", in case the arguments contain spaces in them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.