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

时间:2012-10-02 09:55:49

标签: 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

所以chmod在直接调用execute函数时有效,但在从另一个函数调用时失败,即使调试输出看起来完全相同......

任何人都可以解释这种行为吗?

1 个答案:

答案 0 :(得分:3)

问题是你要覆盖PATH变量,该变量包含二进制文件所在目录的路径,如chmod变量,这就是为什么它找不到它。

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

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