saurabh umathe
saurabh umathe

Reputation: 393

If else condition match statements not working inside shell of jenkinsfile

I have below statement in one of the steps in Jenkinsfile

 steps {
sh '''
file=/sql/common/file1.sql
echo $file
if ["$file" = *"/common"* ]; then
  echo "changes found in common directory "
fi
'''
}

For some reason shell is not working properly inside jenkinsfile. how do we compare strings in shell in Jenkinsfile? do we have any specific syntax for these? Jenkins give error if I use == operator to compare the strings. My assumption was shell should work same way in Jenkinsfile once we declare it inside sh '''. Is that not the case?

Upvotes: 1

Views: 2404

Answers (1)

KamilCuk
KamilCuk

Reputation: 140960

["$file"

is invalid. There must be a space between [ and the argument. [ is a command.

if [ "$file" = *"/common"* ];

doesn't mean what you think it does. *"/common"* undergoes filename expansion, so it is replaced by a list of files that match the pattern. Because there are most probably many files that match the filename expansion, [ program exits with some kind of a a syntax error.

If you want to match a string against a pattern in POSIX shell, either use grep with a regular expression:

if printf "%s\n" "$file" | grep -q '.*/common.*'; then

or use case with glob:

if case "$file" in *"/common"*) true; ;; *) false; ;; esac; then

Upvotes: 2

Related Questions