bash - 从另一个函数调用时,函数中的子 shell 无法找到基本的 bash 命令

标签 bash eval subshell

我有以下 bash 脚本(这是更复杂脚本的简化版本)。

#!/usr/bin/env bash
set -x

function execute() {
    `$1` # same as $($1), gives "command not found" as do all the following:
    # $1 # or ${1}
    # eval "$1"
    # eval $1

    # This gives "No such file or directory" even though it *is* there...
    #"$1"
}

function runCommand() {
    PATH="${1}"
    execute "chmod 777 ${PATH}"
}

execute "chmod 777 ${1}"
runCommand "$1"

#EOF

当我运行它时,我得到以下输出:

+ execute 'chmod 777 build.test-case.sh'
++ chmod 777 build.test-case.sh
+ runCommand build.test-case.sh
+ PATH=build.test-case.sh
+ execute 'chmod 777 build.test-case.sh'
++ chmod 777 build.test-case.sh
./build.test-case.sh: line 5: chmod: command not found

因此,当直接调用 execute 函数时,chmod 可以工作,但当从另一个函数调用它时就会失败,即使调试输出似乎完全相同。 .

谁能解释一下这种行为吗?

最佳答案

问题是您正在覆盖 PATH变量,其中包含二进制文件所在目录的路径,如 chmod 变量,所以这就是它找不到它的原因。

如果您为 runCommand() 函数使用另一个变量,而不是 PATH 变量,它应该可以工作,如下所示:

function runCommand() {
    VAR="${1}"
    execute "chmod 777 ${VAR}"
}

关于bash - 从另一个函数调用时,函数中的子 shell 无法找到基本的 bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12688160/

相关文章:

javascript - 在 Imacros 中的 Eval 语句内围绕双引号分割提取的文本

linux - 为什么在分组命令中执行简单命令不会fork子shell进程,而复合命令会做

linux - 保留返回值并且不从子 shell 运行

bash: `set -e` 在 if 表达式中使用时不起作用?

linux - -bash : ./configure: 没有这样的文件或目录<--尝试安装arping

bash - 如何使用 grep 从最后一行提取百分比?

Bash:检查,如果没有运行则运行一个进程

perl - 如何在 Perl 中评估字符串中的链式表达式?

linux - 将文件名保存为递增数字

Javascript Eval 适用于函数和纯字符串