简体   繁体   中英

Provide input parameters to C code from Linux shell

The concept of my code is like:

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

Usually, after compiling the code and generating the executable main , in the command line we write this to run the code:

./main num=1 input="data.bin"

However, if there's too many arguments, type in the command line each time we run the code is not convenient. So I'm thinking about writing the arguments and run in Linux shell. At first I wrote this:

#! /bin/sh

num = 1
input="data.bin"
./main $(num) $(input)

But error returns:

bash: adj: command not found
bash: input: command not found
bash: adj: command not found
bash: input: command not found

Can anybody help to see and fix it.

There are three main problems with your code:

  1. You can't use spaces around the = when assigning values
  2. You have to use ${var} and not $(var) when expanding values.
  3. The way your code is written, you are passing the string 1 instead of your required string num=1 as the parameter.

Use an array instead:

#!/bin/bash
parameters=(
    num=1
    input="data.bin"
)
./main "${parameters[@]}"

num=1 is here just an array element string with an equals sign in it, and is not related to shell variable assignments.

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