您在示例中显示的bash脚本不会返回正确的目录大小。它将以
4096递归方式返回文件的大小(通常为字节),而不是所有文件和子目录的总大小。如果要获取目录的总大小,可以尝试执行以下操作:
#!groovynode('master') { stage("Get dir size") { script { DIR_SIZE = sh(returnStdout: true, script: 'du -sb /var/jenkins_home/war/jsbundles | cut -f1') } echo "dir size = ${DIR_SIZE}" }}至关重要的部分是使用启用了
shstep的
returnStdout功能,以便您可以在变量内捕获脚本将其输出到控制台的内容。在此示例中,我正在计算
/var/jenkins_home/war/jsbundles文件夹的总大小,当运行此管道脚本时,我得到:
dir size = 653136
然后,您可以
DIR_SIZE在以后的管道步骤中将变量用作输入。
替代方法:使用Groovy的 File.directorySize()
除了使用bash脚本外,您还可以考虑使用Groovy的内置方法
File.directorySize(),例如:
#!groovynode('master') { stage("Get dir size") { script { DIR_SIZE = new File('/var/jenkins_home/war/jsbundles').directorySize() } echo "dir size = ${DIR_SIZE}" }}但是,与使用bash命令的用例相比,此方法将为您提供不同的结果:
dir size = 649040
这是因为Groovy的
File.directorySize()方法以递归方式将结果计算为所有文件大小的总和,而不考虑目录文件的大小。在此示例中,区别是
4096-目录文件的大小
/var/jenkins_home/war/jsbundles(此路径不包含任何子文件夹,仅包含文件堆)。
更新:从类似列的输出中提取数据
您可以通过类似
grep和的管道命令从类似列的输出中提取任何信息
cut。例如,您可以将以上示例替换为:
#!groovynode('master') { stage("Get dir size") { script { DIR_SIZE = sh(returnStdout: true, script: 'ls -la /var | grep jenkins_home | cut -d " " -f5') } echo "dir size = ${DIR_SIZE}" }}对于以下输出:
total 60drwxr-xr-x 1 root root 4096 Nov 4 2017 .drwxr-xr-x 1 root root 4096 May 31 03:27 ..drwxr-xr-x 1 root root 4096 Nov 4 2017 cachedr-xr-xr-x 2 root root 4096 May 9 2017 emptydrwxr-xr-x 2 root root 4096 Nov 4 2017 gitdrwxrwxr-x 20 jenkins jenkins 4096 May 31 12:26 jenkins_homedrwxr-xr-x 5 root root 4096 May 9 2017 libdrwxr-xr-x 2 root root 4096 May 9 2017 localdrwxr-xr-x 3 root root 4096 May 9 2017 lockdrwxr-xr-x 2 root root 4096 May 9 2017 logdrwxr-xr-x 2 root root 4096 May 9 2017 optdrwxr-xr-x 2 root root 4096 May 9 2017 rundrwxr-xr-x 3 root root 4096 May 9 2017 spooldrwxrwxrwt 2 root root 4096 May 9 2017 tmp
它将提取
4096-
jenkins_home文件大小。
值得记住的事情:
- 使用简单的bash脚本,例如
ls -la /var | grep jenkins_home | cut -d " " -f5
。上面显示的示例在我的本地bash和Jenkins服务器中均不起作用 - 将
returnStdout: true
参数添加到sh
step以将命令打印的内容返回到控制台。



