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?

2
  • 1
    Use a function instead of a variable? Commented May 15, 2020 at 21:25
  • 1
    Possible duplicate of this, this, this, this, and many others. (Warning: some of those have answers involving eval -- don't be tempted, eval usually causes weird bugs). Commented May 15, 2020 at 23:46

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

This may achieve what you wanted :

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

Comments