0

In one of my Bash scripts, there's a point where I have a variable SCRIPT which contains the /path/to/an/exe, and what the script ultimately needs to do, is executing that executable. 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.

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.

Enlico
  • 23,259
  • 6
  • 48
  • 102

3 Answers3

3

$($SCRIPT) indeed does not do what you think it does.

The outer $() will execute any commands inside the parenthesis and execute the result string.

The inner $SCRIPT will expand to the value of the SCRIPT variable and execute this string while splitting words on spaces/

If you want to execute the command contained into the SCRIPT variable, you just write as an example:

SCRIPT='/bin/ls'
"$SCRIPT" # Will execute /bin/ls

Now if you also need to handle arguments with your SCRIPT variable command call:

SCRIPT='/bin/ls'
"$SCRIPT" -l # Will execute /bin/ls -l

To also store or build arguments dynamically, you'd need an array instead of a string variable.

Example:

SCRIPT=(/bin/ls -l)
"${SCRIPT[@]}" # Will execute /bin/ls -l

SCRIPT+=(/etc) # Add /etc to the array
"${SCRIPT[@]}" # Will execute /bin/ls -l /etc
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • 1
    The array cases should be `"${SCRIPT[@]}"`; "`$SCRIPT"` expands to only element [0]. – dave_thompson_085 Aug 30 '20 at 16:04
  • I've just understood that I wrote a question other that the one I wanted to ask. I got lost in indirections. However this is the correct answer to the question I asked. [Here's the correct question](https://stackoverflow.com/questions/63660088/execute-command-that-results-from-execution-of-a-script-whose-name-is-in-a-varia). – Enlico Aug 30 '20 at 17:11
2

It worked for me with sh -c:

$ chrome="/opt/google/chrome/chrome" 
$ sh -c "$chrome"
Opening in existing browser session.

It also passed the ShellCheck without any issues.

Hedi Bejaoui
  • 384
  • 2
  • 16
0

with bash, just use $SCRIPT:

cat <<'EOF' > test.sh
SCRIPT='echo aze rty'
$SCRIPT
EOF
bash test.sh

produce:

aze rty
Cyril Jouve
  • 990
  • 5
  • 15