My Bash script sends a set of (multiple) parameters to a C program.
This is my C program:
$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc, char **argv )
{
printf("Parameter 1 is: %s \n", argv[1]);
printf("Parameter 2 is: %s \n", argv[2]);
return 0;
}
Once compiled (as MyCProgram
), it behaves OK:
MyCProgram -f "/path/to/file/with spaces"
Parameter 1 is: -f
Parameter 2 is: /path/to/file/with spaces
But, when trying to send to it parameters via shell variable:
$ var='-f "/path/to/file/with spaces" '
$ MyCProgram $var
Parameter 1 is: -f
Parameter 2 is: "/path/to/file/with
$ MyCProgram "$var"
Parameter 1 is: -f "/path/to/file/with spaces"
Parameter 2 is: (null)
$ MyCProgram '$var'
Parameter 1 is: $var
Parameter 2 is: (null)
$ MyCProgram "$(echo $var)"
Parameter 1 is: -f "/path/to/file/with spaces"
Parameter 2 is: (null)
$ MyCProgram "$(echo "$var")"
Parameter 1 is: -f "/path/to/file/with spaces"
Parameter 2 is: (null)
$ MyCProgram "$(echo '$var')"
Parameter 1 is: $var
Parameter 2 is: (null)
$ MyCProgram '$(echo "$var")'
Parameter 1 is: $(echo "$var")
Parameter 2 is: (null)
$ var="-f '/path/to/file/with spaces' "
$ MyCProgram $var
Parameter 1 is: -f
Parameter 2 is: '/path/to/file/with
How can I obtain the proper behavior, this is, same as when run without shell variables?
Notes:
- Both changes to Bash script or C program are accepted.
- Similar threads that seem to issue a similar question, but I would say that not the same:
Passing quoted arguments to C program in a shell script
Bash: pass variable as a single parameter / shell quote parameter
Upon Craig Estey answer, this works fine:
$ var=(-f "/file with spaces")
$ MyCProgram "${var[@]}"
This method works, but only if I manually (explicitly) assign the value to var
. Assuming var is already assigned (i.e: via input read or file read), I would say the problem here is transferring it to a bash array variable. So:
$ var='-f "/file with spaces"'
$ var2=( $var )
$ MyCProgram "${var2[@]}"
Parameter 1 is: -f
Parameter 2 is: "/file
The problem is still there.