I have a program in C, which takes 2 arguments, filename and text. I want to write a script in bash, which also take 2 arguments, path and file extension, will iterate through all files in given path and give to my program in C as argument files with the givenextension only and text.
Heres my program in C, nothing special really:
#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 my 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 like this: ./script /tmp txt hello
and it should give as arguments all txt
files from /tmp
and 'hello' as text to my C program. No it only shows Give 2 args!
:( Please, help.
Right now you're not actually passing any arguments to the program in your script.
Just pass the arguments normally:
./app "$file" "$text"
I put the arguments in double-quotes to make the shell see the variables as single arguments, in case they contain spaces.
Your arguments come from the command line rather than through standard input. Hence you would use:
./app "$file" "$text"
If it were coming in via standard input (one argument per line), you could use:
( echo "$file" ; echo "$text" ) | ./app
but that's not the case - you need to pass the arguments on the command line for them to show up in argv
.
One other point, you'll notice I've put quotes around the arguments. That's a good idea to preserve whitespace just in case it's important. You should also do that in your lines:
path="$1"
ext="$2"
text="$3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With