I'm trying to write a bash script that takes an environment variable and passes it along to a command.
So if I had something like:
export OUT="-a=arg1 -b=\"arg2.0 arg2.1\""
I want in my bash script to do something like:
<command> -a=arg1 '-b=arg2.0 arg2.1'
I have one approach that seems to do this, but it involves using eval:
eval <command> ${OUT}
If I include set -x
right about the command, I will see:
+ eval <command> a=arg1 'b="arg2.0' 'arg2.1"'
++ <command> -a=arg1 '-b=arg2.0 arg.1'
However, I've poked around the dangers of using eval and since this will be taking the arguments from user input, it's less than ideal.
Since this is bash, I've also considered using arrays to store my arguments and simply put: <command> "$ARRAY[@]"
to do what I want. I've been trying to use IFS, but I'm not sure what I should be splitting on.
For the simplified problem described in the answer above; i.e., turning the following environment variable into three arguments inside a bash script:
Just do the following:
If you're not completely inflexible about the format of
$OUT
, one possibility would be to repeat theoption=
string to allow for concatenation. Then you'd write:If that is acceptable, the following script will work
I can't say I like it much, but it's the closest I've been able to come.
Here's a sample run:
If you import a bash function (for example, in your bash startup file), you can make much better use of arrays. Here's one approach:
For expository purposes,
script.sh
:Example:
In case it's not obvious:
defines a bash function called
command
which does almost nothing (except invoke the builtin:
which does nothing), andexpands to the positional parameters, inserting a dash at the beginning of each one use a find-and-replace substitution. The pattern
#
is actually an empty pattern which only matches at the beginning of the string.