8

我有一个 C 语言程序,它有 2 个参数,文件名和文本。我想在 bash 中编写一个脚本,该脚本还接受 2 个参数,路径和文件扩展名,将遍历给定路径中的所有文件,并将 C 语言中的程序作为参数文件提供给仅具有给定扩展名和文本的参数文件。

这是我的 C 程序,没什么特别的:

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

和我的 bash 脚本:

#!/bin/bash

path=$1
ext=$2
text=$3

for file in $path/*.$ext
do
    ./app | 
    {
        echo $file 
        echo $text
    }
done

我像这样使用它:./script /tmp txt hello它应该将所有txt文件作为参数提供,/tmp并将“你好”作为文本提供给我的 C 程序。不,它只显示Give 2 args!:(请帮忙。

4

3 回答 3

12

现在,您实际上并没有在脚本中将任何参数传递给程序。

只需正常传递参数:

./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.

于 2013-01-30T10:15:51.010 回答
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"
于 2013-01-30T10:15:57.037 回答
2

Your invocation of the application is wrong. It should read

./app $file $text
于 2013-01-30T10:15:51.690 回答