0

I am trying to execute the shell script from outside the jenkinsfile but doesn't seem to work.

#!/bin/bash

basePath=$1
file=$2

path=$basePath/$file
res=$("test -f $path && echo '1' || echo '0' ")

if [ $res == '1' ]
 then
...

The jenkinsfile is

        def basePath = xxx
        ...  
        stage('Prepare') {
            steps {
                script {
                    sh "chmod +x ./scripts/unzip.sh"
                    sh "./scripts/unzip.sh ${basePath} ${params.file}"
                }
            }
        }

I am getting an error at line res=$("test -f $path && echo '1' || echo '0' ") where it says No such file or directory. But the path is valid and it works when I run the command within the jenkinsfile. Not sure why it is giving error when I move the code to another file.

user1298426
  • 3,467
  • 15
  • 50
  • 96

2 Answers2

1

"anything inside double quotes" is a single argument, so there is no executable named literally "test -f $path && echo '1' || echo '0' " on your system. Instead, there is test and echo. Do:

res=$(test -f "$path" && echo 1 || echo 0)

But really, why res? Just:

if test -f "$path"; then

Even with res, then:

test -f "$path"
res=$?
if ((res == 0)); then

Check your scripts with shellcheck .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

When you do a

 x=$("foo bar baz")

the quotes have the effect, that the whole quoted script (foo bar baz) is taken as the name of an executable which is searched in the PATH.

You would receive the same error message, if you would do just a

"test -f $path && echo '1' || echo '0' "

Quote only that part which makes sense to be quoted; in your case

res=$(test -f "$path" && echo 1 || echo 0) 
user1934428
  • 19,864
  • 7
  • 42
  • 87