从另一个函数调用时,函数中的子 shell 无法找到基本的 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
函数被直接调用,但当从另一个函数调用它时会失败,即使调试输出似乎完全相同......
谁能解释这种行为?
解决方案
问题是你正在覆盖 小路 变量,其中包含二进制文件所在目录的路径,例如 chmod
一,所以这就是它找不到它的原因。
如果您使用另一个变量,而不是 PATH
一、为了你的 runCommand()
函数,它应该可以工作,如下所示:
function runCommand() {
VAR="${1}"
execute "chmod 777 ${VAR}"
}
不隶属于 StackOverflow