【问题标题】:Array Concatenation in Shell scriptShell脚本中的数组连接
【发布时间】:2019-12-13 11:59:26
【问题描述】:

我尝试使用一个简单的 shell 脚本来查看 statefulset 的图像,然后在需要时替换它们。

我遇到了这个问题,即存储的数组值没有正确显示.. 这是脚本

#!/bin/bash
##-chronograph3r
##Variables 

read -p "Namespace : " NS

##### To find the Image tags in statefulset 

app=($(kubectl get statefulset -n $NS -o=name | grep "myapp" | cut -c 18-) )
declare app
imgver=($(kubectl get statefulset -n $NS ${array[@]} -o yaml | egrep "image: asia.gcr.io" ))
declare imgver

#--- To display current image version
for i in $@
do
    app[${#app[@]}]=$i
    imglist[${#imgver[@]}]=$i
    echo $i
done
for  (( i==0; i < ${#app[@]}; i++  ))
do
    echo "current image version for ${app[$i]} is ${imgver[$i]}" 
done

期望的输出应该是,

current image version for myapp1 is image: asia.gcr.io/lucifer/myapp:latest
current image version for myapp2 is image: asia.gcr.io/lucifer/myapp:1.4.2
current image version for myapp3 is image: asia.gcr.io/lucifer/myapp:1.3.0
current image version for myapp4 is image: asia.gcr.io/lucifer/myapp:stable

我得到的输出是

current image version for myapp1 is image: asia.gcr.io/lucifer/myapp:latest
current image version for myapp2 is image: 
current image version for myapp3 is image: asia.gcr.io/lucifer/myapp:1.3.0
current image version for myapp4 is image:

当我做“回声 ${imgver[@]}”时

它返回这个

image: asia.gcr.io/lucifer/myapp:latest  image: asia.gcr.io/lucifer/myapp:1.4.2  image: asia.gcr.io/lucifer/myapp:1.3.0  image: asia.gcr.io/lucifer/myapp:stable

我相信连接声明的数组是这里的麻烦制造者。 帮助我在这里找到问题,或者让我知道是否有其他方法可以实现所需的输出。

【问题讨论】:

  • 首先,引用你的变量。特别是${array[@]}$@ 应该是"${array[@]}""$@"。此外,这里不需要declare 命令。顺便说一句,app[${#app[@]}]=... 可以缩写为app+=(...),如果你省略循环,甚至可以缩写为app+=("$@")
  • 为了调试,能否给我们declare -p imgver的输出?
  • 我想我发现了这个问题。罪魁祸首是 image: asia.gcr.io/lucifer/myapp 之后的空格。因此,当存储在 imgver 数组中时,空白之后的每个元素都被视为一个单独的值。因此循环时输出的差异。帮我弄清楚@Socowi 如何做到这一点。
  • 要将cmd 输出的行(包括空格)转换为数组,您可以使用mapfile -t array &lt; &lt;(cmd)

标签: arrays bash shell for-loop concat


【解决方案1】:

感谢@socowi,我解决了这个问题。在执行 declare -p 时,它列出了变量。并且由于空格,字符串 image: 也被视为单独的变量。而不是 egrep 我选择了 awk 并且我能够实现所需的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多