0

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.

2
  • I believe $(something) notation tells bash to run something as a command and use the output. If you want to expand a variable, I believe it should be ${something}. Commented Jul 2, 2018 at 18:12
  • Also num = 1 is not valid bash syntax. Commented Jul 2, 2018 at 18:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What does @ in parameters[@] mean?
@coco: "${parameters[@]}" is how one expands each item in array parameters to a separate token in Bash. You could think of @ in it as "each". For a detailed explanation, see the Shell Parameter Expansion chapter in the Bash Reference Manual.
Then how about remove the double quotes "" in "${parameters[@]}" because it can also come up with the right result.
@coco It won't work if you have spaces or glob characters in your names. For example, input="my input file.bin" will fail

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.