bash - Bash 函数变量命令未找到错误
问题描述
我有一个这样的带有函数的 bash 脚本
_launch()
{
${1}
}
testx()
{
_launch "TESTX=1 ls -la"
}
testx
我在 _launch 函数中收到错误“TESTX=1 command not found”。为什么?当我TESTX=1 ls -la
直接在 shell 上运行时,它工作正常。
解决方案
使用变量来保存命令不是一个好主意。见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
这些变量将作为环境变量传递给启动的命令。
推荐阅读
- go - 使用 go get 从 WSL 2 上的私有 github 存储库中获取依赖项
- mysql - 聚合后Django ORM加入自我
- mongodb - 在 mongodb 上按年分组
- jmeter - 在mac上运行jmeter的问题
- sql - 在同一列的行之间应用条件
- azure-ad-b2c - 用户旅程正文中的 Azure B2C Rest API 为空
- php - PHP,数组-混合顺序,steam api返回不同顺序
- sas - SAS:如何测试一个值在时间之间的稳定性
- javascript - SameSite=Lax 是否应该允许 3rd-party GET?
- python - 如何将外部库导入 Ansible 模块?