首页 > 解决方案 > Bash 函数变量命令未找到错误

问题描述

我有一个这样的带有函数的 bash 脚本

_launch()
{
  ${1}
}

testx()
{
  _launch "TESTX=1 ls -la"
}

testx

我在 _launch 函数中收到错误“TESTX=1 command not found”。为什么?当我TESTX=1 ls -la直接在 shell 上运行时,它工作正常。

标签: bashfunction

解决方案


使用变量来保存命令不是一个好主意。见BashFAQ/050

只要您处理的是可执行文件而不是 shell 内置程序,您就可以这样做:

_launch() {
    env $1
}

var=value如果您在成对使用的值或正在启动的命令的参数中有文字空格,这将不会很好地发挥作用。

您可以通过将命令传递给启动函数并在函数调用本身中设置变量来克服这个问题,如下所示:

_launch() {
    #       your launch prep steps here...
    "$@"  # run the command
    #       post launch code here
}
TESTX=1 TESTY=2 TESTZ=3 _launch ls -la

这些变量将作为环境变量传递给启动的命令。


推荐阅读