How to run a c program in a bash script and give it 2 arguments?

I have a C program that takes 2 arguments, a file name and text. I want to write a script in bash that also takes 2 arguments, a path and a file extension, will iterate over all the files in the specified path and provide my C program as argument files with givenextension and text only.

Here is my C program, nothing special:

#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { if(argc < 3) { fprintf(stderr, "Give 2 args!\n"); exit(-1); } char *arg1 = argv[1]; char *arg2 = argv[2]; fprintf(stdout, "You gave: %s, %s\n", arg1, arg2); return 0; } 

and bash script:

 #!/bin/bash path=$1 ext=$2 text=$3 for file in $path/*.$ext do ./app | { echo $file echo $text } done 

I use it as follows: ./script /tmp txt hello and it should specify as arguments all txt files from /tmp and 'hello' as text to my C program. No, it only shows Give 2 args! :( Please, help.

+6
source share
3 answers

At the moment, you are not actually passing any arguments to the program in the script.

Just pass arguments usually:

 ./app "$file" "$text" 

I put the arguments in double quotes to make the shell see the variables as single arguments if they contain spaces.

+11
source

Your arguments are output from the command line, not through standard input. Therefore, you should use:

 ./app "$file" "$text" 

If it comes through standard input (one argument per line), you can use:

 ( echo "$file" ; echo "$text" ) | ./app 

but this is not the case - you need to pass arguments on the command line so that they appear in argv .

Another point, you'll notice that I put quotation marks around the arguments. It is a good idea to keep spaces just in case it matters. You should also do this in your lines:

 path="$1" ext="$2" text="$3" 
+5
source

Your application call is incorrect. He must read

 ./app $file $text 
+2
source

All Articles