Bash:如何仅更改一个参数值并保持其他参数值保持不变
我有一个bash脚本,该脚本在yaml文件中编辑两个标签,这些值作为参数传递。我如何在运行脚本时只能更新一个标签
#!/bin/bash
#Update UI-ImageTag
sed -i -e '/APP:/{n;n;s/\(imageTag\).*/\1: "'"app-ui-$1"'" /}' \
-e '/APP:/{n;n;n;n;s/\(imageTag\).*/\1: "'"app-db-$2"'" /}' \
values.yaml
并传递参数$ 1和$ 2 ex(./ script.sh.sh 1.0 2.0)的方案,其中两个标签都在values.yaml文件中更新了两个标签。 ,但是当我只给一个参数的值并将另一个参数留为空时(即,仅通过$ 1传递值来执行脚本),则value.yaml文件中的$ 2标签被一个空值替换。 如何更改脚本,以便在我不需要更改app-db的标签的情况下,如果我不以$ 2的价格传递一个值,它会使yaml文件中的旧值保持不变
I have a bash script that edits two tags in a yaml file and these values are passed as parameters. How can I change the script for a scenario where only one tag has to be updated
#!/bin/bash
#Update UI-ImageTag
sed -i -e '/APP:/{n;n;s/\(imageTag\).*/\1: "'"app-ui-$1"'" /}' \
-e '/APP:/{n;n;n;n;s/\(imageTag\).*/\1: "'"app-db-$2"'" /}' \
values.yaml
While running the script and passing values for parameters $1 and $2 Ex(./script.sh 1.0 2.0) both the tags are updated in the values.yaml file, but when I give value for only one parameter and leave the other one empty(i.e., execute the script by passing value for $1 only), then the $2 tag in values.yaml file is replaced with an empty value.
How to change the script so that in a scenario where I dont need to change the tag of app-db and if I dont pass a value for $2, it keeps the old value in the yaml file unchanged
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以要求 shell 在未设置某些内容时提供默认值,只需更改
sed
脚本以捕获旧值并替换为旧值,这样您实际上就不会更改任何内容。仅当设置了
$2
且${2-\\2 时,参数扩展
在未设置时扩展为${2+value}
才会扩展为value
}\2
,在设置时扩展为其值。您会注意到,为此目的,正则表达式也略有更改,以将imageTag
之后的文本捕获到\2
中。You can ask the shell to supply a default value when something is unset, and just change your
sed
script to capture the old value and replace with that, so that you effectively don't change anything.The parameter expansion
${2+value}
expands tovalue
only if$2
is set, and${2-\\2}
expands to\2
when it is unset, and to its value when it's set. You'll notice that the regex was also changed slightly to capture the text afterimageTag
into\2
for this purpose.建议尝试
awk
脚本:未测试,未提供示例数据。
解释:
Suggesting try
awk
script:Not tested, not provided sample data.
Explanation: