8

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.

0

3 Answers 3

13

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.

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

Comments

5

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"

Comments

2

Your invocation of the application is wrong. It should read

./app $file $text

Comments

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.