我尝试在bash脚本中检查所有命令的返回命令。我为这个名为check_command_return_code的函数创建了一个函数。此函数在运行命令的其他函数中调用,除了envsubst命令外,它似乎按预期工作。
这是我的check_command_return_code
check_command_return_code(){
"$@"
if [ "$?" -ne 0 ]; then
echo "[ERROR] Error with command $@"
exit 1
fi
echo "[SUCCESS] Command $@ has successfully run"
}为了在yaml文件中替换env变量,我还编写了这个函数:
substitute_env_variables_into_file(){
echo "Create new file named $2 from $1 by substituting environment variables within it"
check_command_return_code envsubst < $1 > $2
}我称我的函数为这样的替换:
substitute_env_variables_into_file "./ingress-values.yaml" "./ingress-values-subst.yaml"这是我的入口-values.yaml.file文件:
controller:
replicaCount: 2
service:
loadBalancerIP: "$INTERNAL_LOAD_BALANCER_IP"
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true" 我想我的入口-价值-物质。亚姆看起来是这样:
controller:
replicaCount: 2
service:
loadBalancerIP: "my_private_ip"
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal:不幸的是,ingress values subst.yaml是用我的check_command_return_code函数的回声展开的,如您所见:
controller:
replicaCount: 2
service:
loadBalancerIP: "my_private_ip"
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
[SUCCESS] Command envsubst has successfully run由于以下命令,我启用了“调试”模式,以便有更详细的内容:
set -x这些日志是我的脚本输出的日志:
++ substitute_env_variables_into_file ./private-ingress-values.yaml ./private-ingress-values-subst.yaml
++ echo 'Create new file named ./ingress/private-ingress-values-subst.yaml from ./private-ingress-values.yaml by substituting environment variables within it'
Create new file named ./private-ingress-values-subst.yaml from ./private-ingress-values.yaml by substituting environment variables within it
++ check_command_return_code envsubst
++ envsubst
++ '[' 0 -ne 0 ']'
++ echo '[SUCCESS] Command envsubst has successfully run'我不明白为什么命令envsubst的参数不传递到我的check_command_return_code函数中,就像您在前面的日志中看到的那样。
提前感谢您的帮助
发布于 2022-11-18 13:40:14
我不明白为什么我的命令envsubst的参数没有传递到我的check_command_return_code
重定向不是参数。重定向在执行行时打开。
当您执行your_function > file时,your_function标准输出将在整个函数期间被重定向到file,包括your_function中的所有命令。
将它封装在另一个函数中:
myenvsubst() {
envsubst < "$1" > "$2"
}
check_command_return_code myenvsubst "$1" "$2"或者更好的是,将日志信息写入标准错误或其他文件描述符。
echo "[ERROR] Error with command $*" >&2使用shellcheck检查您的脚本,以发现以下问题:
< $1 > $2
没有被引用。他们应该是< "$1" > "$2"
if "$?“-ne 0;然后
是反模式。更喜欢if ! "$@"; then。
回波“$@命令错误”
是引用的$@的一个奇怪用法。更喜欢$*,或者转到单独的参数。
https://stackoverflow.com/questions/74490455
复制相似问题