Problem
I would like to use the parameters given to a script as is – with quotes and everything. So far, all solutions I found strip the quotes, or do something subtly different.
Scenario
I have a tool that accepts strings as command line parameters, for instance
./tool --formula="AG EF phi;"
I further have a wrapper script that should call the script. Its invocation should be
wrap.sh ./tool --formula="AG EF phi;"
This script does something like
# preparation phase
# ...
# call tool and remember exit code
$*
result=$?
# evaluation phase
# ...
exit $result
Unfortunately, the tool is then called as
./tool --formula=AG EF phi;
which is not the same as above and would yield a syntax error. The only hacks I found would give me something like
./tool "--formula=AG EF phi;"
which is also wrong.
Details
To be concrete, here is some dummy code to exemplify the problem:
First, the C program “tool.c”.
#include <stdio.h>
int main(int argc, char** argv) {
int i;
for (i = 0; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
return 0;
}
Then, the wrap script “wrap.sh”:
#!/bin/bash
echo $*
$*
exit $?
Now here is what I tried:
$ ./tool --formula="Foo bar"
0: ./tool
1: --formula=Foo bar
$ ./wrap.sh ./tool --formula="Foo bar"
./tool --formula=Foo bar
0: ./tool
1: --formula=Foo
2: bar
$ ./wrap.sh ./tool --formula="\"Foo bar\""
./tool --formula="Foo bar"
0: ./tool
1: --formula="Foo
2: bar"
$ ./wrap.sh ./tool --formula="\"Foo bar\""
./tool --formula="Foo bar"
0: ./tool
1: --formula="Foo
2: bar"
$ ./wrap.sh "./tool --formula=\"\\\"Foo bar\\\"\""
./tool --formula="\"Foo bar\""
0: ./tool
1: --formula="\"Foo
2: bar\""
And here is what I want (for whatever necessary change in the wrap script):
$ ./wrap.sh ./tool --formula="Foo bar"
0: ./tool
1: --formula=Foo bar
Proposals
Escape Quotes
When I escape quotes like Shabaz proposed, the variable $* contains correctly quoted strings, for instance:
wrap.sh ./tool --formula="\"AG EF phi;\""
and then in wrap.sh the code:
echo $*
would produce
./tool --formula="AG EF phi;"
However, executing $* produces the exact error as above: The argument of formula is stripped after “AG”. Furthermore, it would be nice not to escape quotes.
Could a different shell help?
You can use this script that works to preserve the white-spaces you want:
Execute above script using this command line:
OUTPUT: