2012-10-02 8 views
2

我有以下bash脚本(这是更复杂脚本的简化版本)。函数中的子壳从另一个函数调用时找不到基本的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函数直接调用,但失败时,它从另一个函数调用,即使调试输出似乎要完全一样...

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

回答

3

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

如果您使用另一个变量,而不是一个PATH,为您runCommand()功能,它应该工作,像这样:

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

嗯,这是鸡蛋在我的脸上,然后。这会教会我不遵守我从未使用过所有瓶盖变量的标准。 :-) – Potherca

相关问题