0

I have an external executable that I need to pass arguments to. With a bash script, I have code that determines these arguments. Some arguments may have escaped spaces. I need to then execute that string, without expanding each of the arguments.

# ... some code that determines argument string
# the following is an example of the string

ARGSTR='./executable test\ file.txt arg2=true'
exec ${ARGSTR}

I must have the $ARGSTR be expanded so that I can pass arguments to ./executable, but each of the arguments should not be expanded. I have tried quoting "test file.txt", but this still does not pass it as one argument to ./executable.

Is there a way to do something like this?

k-a-v
  • 326
  • 5
  • 22
  • 1
    Use a function instead of a variable? – Jetchisel May 15 '20 at 21:25
  • 1
    Possible duplicate of [this](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables), [this](https://stackoverflow.com/questions/5615717/how-to-store-a-command-in-a-variable-in-a-shell-script), [this](https://stackoverflow.com/questions/13365553/setting-an-argument-with-bash), [this](https://stackoverflow.com/questions/7454526/variable-containing-multiple-args-with-quotes-in-bash), and many others. (Warning: some of those have answers involving `eval` -- don't be tempted, `eval` usually causes weird bugs). – Gordon Davisson May 15 '20 at 23:46

2 Answers2

3

Us an array instead of a string:

#!/usr/bin/env bash

ARGSTR=('./executable' 'test file.txt' 'arg2=true')
exec "${ARGSTR[@]}"

See:

BashFAQ-50 - I'm trying to put a command in a variable, but the complex cases always fail.

https://stackoverflow.com/a/44055875/7939871

Community
  • 1
  • 1
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
1

This may achieve what you wanted :

ARGSTR='./executable test\ file.txt arg2=true'
exec bash -c "exec ${ARGSTR}"
Philippe
  • 20,025
  • 2
  • 23
  • 32