I am not able to parse the arguments of a script properly. The scenario is explained below.

First script (test2.sh):

#! /bin/sh
arg_part1="./test1.sh '123 789'"

#Option 1
${arg_part1} ${arg_part2} 

#Option 2
$("$arg_part1" arg_part2)

Second script (test1.sh):

#! /bin/sh
echo "Hello World $1 $2"


Hello World '123 789'
./test1.sh '123 789': No such file or directory

Desired output:

Hello World 123 789 456

The '123 789' should be processed as first argument and 456 should be my second argument. Note: I do not have the option of breaking up arg_part1 in two different variables.


You could keep using the split+glob operator (those unquoted ${arg_part1} and ${arg_part2}), but use a different separator for the split part (as some of the elements contain one of the default separators (space)). You'd also want to disable the glob part.

#! /bin/sh
arg_part1='./test1.sh|123 789'

IFS='|'  # split unquoted expansions on | instead of default SPC+TAB+NL
set -o noglob # disable the glob part (not that it would have any effect
              # in this particular case).

$arg_part1 $arg_part2 # invoke split+glob

# or since you're not intending to split $arg_part2
$arg_part1 "$arg_part2"

To store code, functions are often more appropriate than variables:

arg_part1() { ./test1.sh '123 789' "$@"; }

arg_part1 "$arg_part2"

and you don't have to mess-up with the split+glob operator, or use the dangerous eval.


I think you're "stuck" needing to use eval here, so that arg_part1 is reinterpreted as a command string, which is then parsed into a command and arguments:

#! /bin/sh
arg_part1="./test1.sh '123 789'"
eval "${arg_part1}" "${arg_part2}"


Hello World 123 789 456

Debug output:

$ sh -x test2.sh
+ arg_part1='./test1.sh '\''123 789'\'''
+ arg_part2=456
+ eval './test1.sh '\''123 789'\''' 456
++ ./test1.sh '123 789' 456
Hello World 123 789 456

Note that since you've inner-quoted '123 789', they appear as a single $1 argument to test1.sh.

  • Even though you're using eval, the variables should still be quoted to prevent filename expansion: eval "$arg_part1 $arg_part2" Nov 16 '17 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.