Jenkinsfile -从另一个文件引用shell脚本时找不到文件



我试图从jenkinsfile外部执行shell脚本,但似乎不工作。

#!/bin/bash
basePath=$1
file=$2
path=$basePath/$file
res=$("test -f $path && echo '1' || echo '0' ")
if [ $res == '1' ]
then
...

jenkins文件

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

我在res=$("test -f $path && echo '1' || echo '0' ")行得到一个错误,它说No such file or directory。但是该路径是有效的,并且当我在jenkinsfile中运行命令时它可以工作。不知道为什么当我将代码移动到另一个文件时给出错误。

"anything inside double quotes"是一个单独的参数,因此在您的系统上没有字面上命名为"test -f $path && echo '1' || echo '0' "的可执行文件。取而代之的是testecho。做的事:

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

但说真的,为什么呢?只是:

if test -f "$path"; then

即使有res,那么:

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

使用shellcheck检查你的脚本。

当你做

x=$("foo bar baz")

加引号的效果是,整个加引号的脚本(foo bar baz)将作为在PATH中搜索的可执行文件的名称。

您将收到相同的错误信息,如果您只执行

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

只引用有意义的部分;

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