我的代码的概念是这样的:
#include <stdio.h>
int main(int argc, char *argv[])
{
int num;
FILE *fp;
getint("num",&num); /* This line is pseudo-code. The first argument is key for argument, the second is the variable storing the input value */
fp = inputfile("input"); /* This line is pseudo-code. The argument is key for argument, fp stores the return file pointer */
...
...
exit(0);
}
通常,编译代码并生成可执行文件main
后,我们在命令行中编写以下代码来运行代码:
./main num=1 input="data.bin"
但是,如果参数太多,每次运行代码时都在命令行中输入就不太方便了。所以我正在考虑编写参数并在 Linux shell 中运行。一开始我是这样写的:
#! /bin/sh
num = 1
input="data.bin"
./main $(num) $(input)
但错误返回:
bash: adj: command not found
bash: input: command not found
bash: adj: command not found
bash: input: command not found
任何人都可以帮忙查看并修复它吗?
最佳答案
您的代码存在三个主要问题:
- 赋值时不能在
=
两边使用空格 - 扩展值时必须使用
${var}
而不是$(var)
。 - 按照代码编写方式,您将传递字符串
1
而不是所需的字符串num=1
作为参数。
使用数组代替:
#!/bin/bash
parameters=(
num=1
input="data.bin"
)
./main "${parameters[@]}"
num=1
这里只是一个带有等号的数组元素字符串,与 shell 变量赋值无关。
关于c - 从 Linux shell 向 C 代码提供输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51141615/