bashcommand-substitutionindirectionshellcheckmultiple-indirection

Execute command that results from execution of a script whose name is in a variable


When posting this question originally, I totally misworded it, obtaining another, reasonable but different question, which was correctly answered here.

The following is the correct version of the question I originally wanted to ask.

In one of my Bash scripts, there's a point where I have a variable SCRIPT which contains the /path/to/an/exe which, when executed, outputs a line to be executed.

What my script ultimately needs to do, is executing that line to be executed. Therefore the last line of the script is

$($SCRIPT)

so that $SCRIPT is expanded to /path/to/an/exe, and $(/path/to/an/exe) executes the executable and gives back the line to be executed, which is then executed.

However, running shellcheck on the script generates this error:

In setscreens.sh line 7:
$($SCRIPT)
^--------^ SC2091: Remove surrounding $() to avoid executing output.

For more information:
  https://www.shellcheck.net/wiki/SC2091 -- Remove surrounding $() to avoid e...

Is there a way I can rewrite that $($SCRIPT) in a more appropriate way? eval does not seem to be of much help here.


Solution

  • If the script outputs a shell command line to execute, the correct way to do that is:

    eval "$("$SCRIPT")"
    

    $($SCRIPT) would only happen to work if the command can be completely evaluated using nothing but word splitting and pathname expansion, which is generally a rare situation. If the program instead outputs e.g. grep "Hello World" or cmd > file.txt then you will need eval or equivalent.