Zsh中执行变量报错:Terraform/Terragrunt自定义函数运行故障排查
在Zsh中正确执行变量形式命令的解决方案
问题描述
我编写了一个基础Zsh函数t,逻辑如下:
t() { [[ -f ./terragrunt.hcl ]] && local exe=terragrunt [[ ! -f ./terragrunt.hcl ]] && local exe=terraform [[ ! $exe ]] && echo -e "\033[31;1m[ERROR]\033[0m Can't figure out what to run. Please run manually" local cmd="$exe $@" [[ $DEBUG ]] && echo -e "\033[34;1m[DEBUG]\033[0m executable is $exe. Args are $@ Command to be run: $cmd" $cmd }
执行t outputs时,返回错误信息:t:9: command not found: terraform output,但直接执行terraform output可得到正常结果。尝试过eval和return均无效,请问在Zsh中如何正确执行变量形式的命令?
问题原因
错误核心在于将命令和参数拼接成单个字符串变量$cmd,Zsh解析时会把整个字符串当成单个命令名查找,而非拆分命令与参数。比如exe=terraform、$@为outputs时,$cmd变成terraform outputs,Zsh会寻找名为terraform outputs的命令,自然找不到,从而报错。
解决方案
无需拼接字符串,推荐两种可靠写法:
写法一:直接执行(最简洁)
去掉cmd变量,直接用$exe "$@"执行,Zsh会正确识别命令与参数:
t() { local exe if [[ -f ./terragrunt.hcl ]]; then exe=terragrunt else exe=terraform fi if [[ ! $exe ]]; then echo -e "\033[31;1m[ERROR]\033[0m Can't figure out what to run. Please run manually" return 1 # 错误时返回非0状态码,符合Shell惯例 fi if [[ $DEBUG ]]; then echo -e "\033[34;1m[DEBUG]\033[0m executable is $exe. Args are $@ Command to be run: $exe $@" fi $exe "$@" }
写法二:数组存储命令(适合复杂场景)
若需后续修改命令参数,用数组存储更安全,避免字符串拼接的解析问题:
t() { local exe [[ -f ./terragrunt.hcl ]] && exe=terragrunt || exe=terraform [[ ! $exe ]] && { echo -e "\033[31;1m[ERROR]\033[0m Can't figure out what to run. Please run manually" return 1 } local cmd=($exe "$@") # 数组存储命令与参数 [[ $DEBUG ]] && echo -e "\033[34;1m[DEBUG]\033[0m executable is $exe. Args are $@ Command to be run: ${cmd[*]}" "${cmd[@]}" # 执行数组中的命令,双引号保证参数正确解析 }
补充说明
- 若之前用
eval $cmd无效,是因为当参数含空格或特殊字符时,eval会存在安全风险,且参数可能未正确转义。直接用数组或命令加参数的方式比eval更安全可靠。 - 加入
return 1是为了让函数在出错时返回非0退出状态码,符合Shell脚本惯例,方便后续判断执行结果。
内容的提问来源于stack exchange,提问作者Josh Beauregard
相关产品推荐
相关产品推荐

