在sh中读取文件时,while循环不起作用

时间:2019-10-24 19:29:08

标签: jenkins-pipeline sh

我在Jenkinsfile中部署了以下shell脚本

withEnv(['PATH+EXTRA=/busybox:/kaniko']) {
  sh """#!/busybox/sh
    cat "images2.txt"
    cat "images2.txt" | while read line || [ -n "\$line" ]; do
      fields=(\$line)
      echo "FROM \${fields[0]}" | /kaniko/executor --dockerfile /dev/stdin --destination \${fields[1]}
    done
"""
}

我必须对$进行转义,因为它位于Jenkins文件中,否则Groovy不会期望它。

images2.txt的内容是:

docker.io/prom/blackbox-exporter:v0.14.0 eu.gcr.io/development/infra/monitoring/blackbox-exporter:v0.14.0
docker.io/busybox:1.30.0 eu.gcr.io/development/infra/monitoring/busybox:1.30.0

管道运行时,我得到了错误

/home/jenkins/agent/workspace/test-job@tmp/durable-9cce3aab/script.sh: line 4: syntax error: unexpected "(" (expecting "done")

我也尝试过做类似的事情

sh """#!/busybox/sh
input="images2.txt"
while IFS= read -r line
  do
    fields=(\$line)
    echo "FROM \${fields[0]}" | /kaniko/executor --dockerfile /dev/stdin --destination \${fields[1]}
  done < "\$input" 
"""

但是结果是一样的。知道这里可能有什么问题吗?

1 个答案:

答案 0 :(得分:0)

按照@Charles Duffy的建议,我实现了

sh """#!/busybox/sh
cat "images2.txt" | while read field1 field2 rest; do
  echo "FROM \$field1" | /kaniko/executor --dockerfile /dev/stdin --destination \$field2
done
""" 

,效果很好。