0

Here is a script newbie question. I am invoking a script as follows (not space in hello world):

$ ALL_ARGS="-t 30 -h 'hello world'" ./test.sh

Inside test.sh I would like to pass the parameters in ALL_ARGS as 4 separate parameters, but without using the 'eval' call.

#!/bin/bash

#my_function should receive 4 parameters
#

my_function () { 
    printf "'%s' " "$1"
    printf "'%s' " "$2"
    printf "'%s' " "$3"
    printf "'%s' " "$4"
    echo ""
}

echo "Desired Output, but without using eval"
# my_function '-t' '30' '-h' 'hello world'
eval "my_function $(echo $ALL_ARGS)"

As you can see, I am calling my_function from inside my script and passing in the value of $ALL_ARGS. The problem is the "space" in the $ALL_ARGS. The following attempts have failed, for various reasons:

my_function $(echo $ALL_ARGS)
my_function $(echo "$ALL_ARGS")
my_function "$(echo "$ALL_ARGS")"
my_function "$(echo $ALL_ARGS)"
my_function "$ALL_ARGS"
my_function $ALL_ARGS

In essence, I want the call to look something like this when it executes in the script:

my_function -t 30 -h 'hello world'

Thanks.

Alex Paransky
  • 985
  • 2
  • 10
  • 21
  • Let me see if I understand: You want to provide multiple configuration commands and a main arguments at the end, right? – Bruno Peixoto Apr 25 '22 at 17:21
  • 1
    Arrays were introduced as a replacement for trying to use regular parameters to store lists of distinct values. Unfortunately, you can't export an array as an environment variable (at least, not without destroying the structure arrays provide in the first place). – chepner Apr 25 '22 at 17:27
  • See [Reading quoted/escaped arguments correctly from a string](https://stackoverflow.com/questions/26067249/reading-quoted-escaped-arguments-correctly-from-a-string) (which I've added to the list of linked duplicates) – Charles Duffy Apr 25 '22 at 17:42
  • 1
    BTW, note that `printf "'%s' " "$1"` is very much not sufficient to make data eval-safe. Consider what it does if your `$1` is `$(rm -rf ~)'$(rm -rf ~)'`, with literal `'`s as part of the data. – Charles Duffy Apr 25 '22 at 17:51

0 Answers0