【问题标题】:Linux command to delete directory except specific directory fail in shell script of pipelineLinux命令删除特定目录以外的目录在管道的shell脚本中失败
【发布时间】:2020-04-24 10:19:51
【问题描述】:

/home/oracle/jenkins/workspace/test/ 位置,我有多个目录。我想删除除test1 之外的所有目录,我使用终端中的以下内容 -

rm -rf /home/oracle/jenkins/workspace/test/!("test1")

同样我想通过 Jenkins 管道实现,因此编写了方法 -

def cleanWorkspaceDir() {
    echo "Cleaning workspace"
    sh '''rm -rf /home/oracle/jenkins/workspace/test/!("test1")
    '''
}

但它给出了错误 - /home/oracle/jenkins/workspace/RedmineAndReviewboardProject/SVNCheckout@tmp/durable-810bac2b/script.sh: line 1: syntax error near unexpected token('`

您能帮我解决这个问题吗?

【问题讨论】:

  • def cleanWorkspaceDir() { 不是 POSIX shell 中的有效命令。
  • 查看here如何编写正确的函数定义。
  • 该方法是 Jenkins 流水线代码中定义的 groovy 方法。
  • 那么你为什么将它作为 shell 脚本运行,而不是作为 groovy 程序运行呢?
  • 在 groovy 中,除了目录中的特定目录之外,我找不到删除目录的方法,就像我们在 linux 中那样。

标签: shell jenkins jenkins-pipeline sh jenkins-groovy


【解决方案1】:

您可以尝试以下方法:

def cleanWorkspaceDir() {
    echo "Cleaning workspace"
    sh '''find test/ -mindepth 1 '!' -name test1 -type d -exec rm -rf '{}' +
    '''
}

pipeline {
   agent { label 'slave' }

   stages {
      stage('Hello') {
         steps {
            sh 'mkdir -p test/{a/{p,q},b,c/{r,s},test1,test2}'
            sh 'ls -lR'
            cleanWorkspaceDir()
         }
      }
   }
}

将上面的find 命令替换为以下任意一种:

find /home/oracle/jenkins/workspace/test/ -mindepth 1 -type d -not -name test1 -delete

find /home/oracle/jenkins/workspace/test/ -mindepth 1 ! -name 'test1' -type d -exec rm -rf {} +

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 2010-10-20
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    相关资源
    最近更新 更多