简体   繁体   中英

Jenkins sh run with functions

I have the following script. Unfortunately I not able to get it run on Jenkins.

#!/bin/bash
function pushImage () {
    local serviceName=$1
    local version=$(getImageVersionTag $serviceName)
    cd ./dist/$serviceName
    docker build -t $serviceName .
    docker tag $serviceName gcr.io/$PROJECT_ID/$serviceName:$version
    docker tag $serviceName gcr.io/$PROJECT_ID/$serviceName:latest
    docker push gcr.io/$PROJECT_ID/$serviceName
    cd ../..
}

function getImageVersionTag () {
    local serviceName=$1

    if [ $BUILD_ENV = "dev" ];
    then
        echo $(timestamp)
    else
        if [ $serviceName = "api" ];
        then
            echo $(git tag -l --sort=v:refname | tail -1 | awk -F. '{print $1"-"$2"-"$3"-"$4}')
        else
            echo $(git tag -l --sort=refname | tail -1 | awk -F. '{print $1"-"$2"-"$3"-"$4}')
        fi
    fi
}

function timestamp () {
    echo $(date +%s%3N)
}

set -x
## might be api or static-content
pushImage $1

I'm receiving this error on Jenkins

10:10:17 + sh push-image.sh api
10:10:17 push-image.sh: 2: push-image.sh: Syntax error: "(" unexpected

I already configured Jenkins global parameter to /bin/bash as default shell execute environment, but still having same error.

The main issue here in usage of functions, as other scripts that has been executed successfully don't have any.

How this can be fixed?

Short answer: make sure you're running bash and not sh

Long answer: sh (which is run here despite your effort of adding a shebang) is the bourne shell and does not understand the function keyword. Simply removing it will solve your issue.

Please note however that all your variable expansions should be quoted to prevent against word splitting and globbing. Ex: local version=$(getImageVersionTag "$serviceName")

See shellcheck.net for more problems appearing in your file (usage of local var=$(...) ) and explicit list of snippets which are missing quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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