Search code examples
bashshellenvironment-variablesexec

Passing multiple concatened commands to a exec statement fails


I have a script (starter.sh) that simply contains the following:

#!/usr/bin/env bash
exec "$@"

The script is configured to exec the content of a certain environment variable (i.e. COMMAND)

If the environment variable contains a single command, it works:

 COMMAND='unzip myfile.zip'

But if I try to concatenate several commands (with && or ;) it fails:

COMMAND='unzip myfile.zip && cd /home'

with the error:

caution: filename not matched

The error is obviously raised by the unzip command that get confused by the && that somehow is no longer interpreted as concatenation.

The question is if there is any way whatsoever to pass a concatenated list of commands to an exec statement without modifying the exec call in the file "starter.sh" The only option I have is to modify the content of the environment variable to a list of commands (not a path to a shell file that would be a obvious solution otherwise)


Solution

  • From the docs:

    exec: exec [-cl] [-a name] file [redirection ...] Exec FILE, replacing this shell with the specified program.

    That is, exec expects a file to execute. Then when you add more than one command the whole string is trying to be interpreted as a file name.

    So if you want to pass something that's not a file name then don't use exec.