0

I start programming in c language, and I ask myself this question.

I have a file lol.c :

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
    printf ("argc\t= %d\n", argc);

    for (int i=0; i < argc; i++)
        printf ("argv[%i]\t= %s\n", i, argv[i]);

    return 0;
}

So when I execute the file (after compilation) :

./lol "abc" "def"

He returns so :

argc    = 3
argv[0] = ./lol
argv[1] = abc
argv[2] = def

Now, I have a bash script lol.sh :

#!/bin/bash

./lol "abc"

When I execute the file :

bash lol.sh def

So we get :

argc    = 2
argv[0] = ./lol
argv[1] = abc

How to retrieve the positional parameters passed to the bash script (from the file lol.c) ?

My first solution is to pass the positional parameters to the lol command like this (lol.sh) :

#!/bin/bash

./lol "abc" "$*"

He returns so :

argc    = 3
argv[0] = ./lol
argv[1] = abc
argv[2] = def

I am not very satisfied with this solution, is there another way for that ?

Thanks

Momonosoke
  • 145
  • 1
  • 9

1 Answers1

0

While "$*" works, it mashes all the arguments into one, with a space separating the original arguments. You could see this by running:

bash lol.sh def ghi jkl

which would produce:

argc    = 3
argv[0] = ./lol
argv[1] = abc
argv[2] = def ghi jkl

and running bash lol.sh would produce:

argc    = 3
argv[0] = ./lol
argv[1] = abc
argv[2] = 

Using "$*" is seldom the correct notation; you should normally use "$@" which relays the arguments verbatim as separate arguments, and handles 'no arguments' correctly (whereas "$*" creates an empty string as an argument).

This command should do what you want:

./lol "abc" "$@"

Then the output from bash lol.sh def ghi jkl would be:

argc    = 5
argv[0] = ./lol
argv[1] = abc
argv[2] = def
argv[3] = ghi
argv[4] = jkl

and the output from bash lol.sh would be:

argc    = 2
argv[0] = ./lol
argv[1] = abc

See also How to iterate over arguments in a bash script?)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278