【问题标题】:Executing the output as filename将输出作为文件名执行
【发布时间】:2020-12-18 21:00:36
【问题描述】:

在我的一个 Bash 脚本中,我有一个变量 SCRIPT,其中包含 /path/to/an/exe,而脚本最终需要做的是执行该可执行文件。因此脚本的最后一行是

$($SCRIPT)

这样$SCRIPT 被扩展为/path/to/an/exe$(/path/to/an/exe) 执行可执行文件。

但是,在脚本上运行 shellcheck 会产生此错误:

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...

有没有办法可以更合适的方式重写$($SCRIPT)eval 在这里似乎没有太大帮助。

【问题讨论】:

    标签: bash command-substitution indirection shellcheck multiple-indirection


    【解决方案1】:

    使用 bash,只需使用 $SCRIPT:

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

    生产:

    aze rty
    

    【讨论】:

      【解决方案2】:

      sh -c 对我有用:

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

      它也顺利通过了ShellCheck

      【讨论】:

        【解决方案3】:

        $($SCRIPT) 确实不像你想的那样做。

        外层$()会执行括号内的任何命令并执行结果字符串。

        内部$SCRIPT 将扩展为SCRIPT 变量的值并执行此字符串同时在空格上拆分单词/

        如果你想执行包含在SCRIPT变量中的命令,你只需写一个例子:

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

        现在,如果您还需要使用 SCRIPT 变量命令调用处理参数:

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

        要动态存储或构建参数,您需要一个数组而不是字符串变量。

        例子:

        SCRIPT=(/bin/ls -l)
        "${SCRIPT[@]}" # Will execute /bin/ls -l
        
        SCRIPT+=(/etc) # Add /etc to the array
        "${SCRIPT[@]}" # Will execute /bin/ls -l /etc
        

        【讨论】:

        • 数组case应该是"${SCRIPT[@]}"; "$SCRIPT" 仅扩展为元素 [0]。
        • 我刚刚明白,我写了一个问题,而我想问的不是这个问题。我迷失在间接中。然而,这是我提出的问题的正确答案。 Here's the correct question.
        猜你喜欢
        • 2013-03-28
        • 1970-01-01
        • 2014-01-11
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        相关资源
        最近更新 更多