我有一个C程序,它有2个参数,文件名和文本.我想在bash中编写一个脚本,它还带有2个参数,路径和文件扩展名,将遍历给定路径中的所有文件,并在C中作为参数文件提供给我的程序,仅包含givenextension和text.
继承我的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,它应该将来自/ tmp和’hello’的所有txt文件作为参数提供给我的C程序.不,它只显示Give 2 args! :( 请帮忙.
现在你实际上并没有在脚本中向程序传递任何参数.
通常传递参数:
- ./app "$file" "$text"
我将参数放在双引号中,以使shell将变量视为单个参数,以防它们包含空格.