简体   繁体   English

在 Jenkins bash 脚本中转义 sed 命令

[英]Escape sed command in Jenkins bash script

I have a Bash script working fine locally, now I am trying to put it in Jenkinsfile to run as its pipeline:我有一个在本地运行良好的 Bash 脚本,现在我正试图将它放在 Jenkinsfile 中作为其管道运行:

    stage('Update Cloudfront'){
      steps {
        sh '''
            #!/bin/bash
            YAML_FILE="path/to/values.yaml"
            DATE="$(date '+%d-%m-%Y')"
            wget https://www.cloudflare.com/ips-v4 && wget https://www.cloudflare.com/ips-v6
            CLOUDFLARE_NEW=$(awk '{printf fmt,$1}' fmt="%s\n" ips-v4 ips-v6 | paste -sd, -)
            CLOUDFLARE_OLD=$(yq -r .controller.config.proxy-real-ip-cidr $YAML_FILE | sed -E 's/\,37\.16\.11\.30\/32//')
            if [[ "$CLOUDFLARE_NEW" == "$CLOUDFLARE_OLD" ]]; then
              echo "No need to do anything"
            else
              echo "Cloudflare IP ranges change detected, updating Nginx value file"
              CLOUDFLARE_NEW=$(awk '{printf fmt,$1}' fmt="%s\n" ips-v4 ips-v6 | paste -sd, -) yq e '.controller.config.proxy-real-ip-cidr = env(CLOUDFLARE_NEW)' -i $YAML_FILE
              echo "Add third party IP range"
              yq e '.controller.config.proxy-real-ip-cidr +=",1.2.3.4/32"' -i $YAML_FILE
            fi
        '''
      }
    }//end stage('Update Cloudfront')

Unfortunately it won't work:不幸的是,它不起作用:

WorkflowScript: 73: unexpected char: '\' @ line 73, column 113.
   cidr $YAML_FILE | sed -E \\"s/\,37\.16\.
                                 ^

I've tried to escape it with \\"s/\,37\.16\.11\.30\/32//\\" etc. but it doesn't work either.我试图用\\"s/\,37\.16\.11\.30\/32//\\"等来逃避它,但它也不起作用。 I've tried with double and single quotes with no luck.我试过双引号和单引号但没有运气。

You can avoid all the escaping by using a character class and different regex delimiters, like so:您可以通过使用字符类和不同的正则表达式分隔符来避免所有转义,如下所示:

sed -e 's#,37[.]16[.]11[.]30/32##'

In the event you do need to escape something though, simply doubling the backslash should do it:如果您确实需要转义某些内容,只需将反斜杠加倍即可:

sed -e 's/,37\\.16\\.11\\.30\\/32//'

Though, given the number of levels involved here, it might need double escaping:不过,考虑到此处涉及的级别数量,它可能需要双重转义:

sed -e 's/,37\\\\.16\\\\.11\\\\.30\\\\/32//'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM