简体   繁体   中英

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

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"

Your invocation of the application is wrong. It should read

./app $file $text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM