C语言 如何在bash脚本中运行ac程序并给它2个参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14601430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:12:22  来源:igfitidea点击:

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

cbashshell

提问by Katie

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.

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

Heres my program in C, nothing special really:

这是我的 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;
}

and my bash script:

和我的 bash 脚本:

#!/bin/bash

path=
ext=
text=

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

I use it like this: ./script /tmp txt helloand it should give as arguments all txtfiles from /tmpand 'hello' as text to my C program. No it only shows Give 2 args!:( Please, help.

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

回答by Some programmer dude

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.

我将参数放在双引号中,以使 shell 将变量视为单个参数,以防它们包含空格。

回答by paxdiablo

Your arguments come from the command line rather than through standard input. Hence you would use:

您的参数来自命令行而不是标准输入。因此,您将使用:

./app "$file" "$text"

If it werecoming 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.

但事实并非如此 - 您需要在命令行上传递参数,以便它们显示在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=""
ext=""
text=""

回答by junix

Your invocation of the application is wrong. It should read

您对应用程序的调用是错误的。它应该读

./app $file $text