首页 > 解决方案 > Bash - 目录名:缺少操作数

问题描述

我的管道获取terragrunt.hcl文件的目录并对其运行一堆测试。如果我的if陈述为真,我希望我的 bash 执行 2 个命令,如果不是真的跳转到该else陈述,我else应该什么都不做并退出。terragrunt.hcl下面的这个 bash 实际上可以工作,但是只要不触摸a ,我就会在管道日志中得到这个错误。如果我的if陈述不正确,我会假设一些事情!

这是我的狂欢:

#!/bin/bash

if find . -name "terragrunt.hcl" -print0 | xargs -0 git diff-tree --no-commit-id --name-only -r $CI_COMMIT_SHA ; then # output only latest terragrunt.hcl commit
   find . -name "terragrunt.hcl" -print0 | xargs -0 git diff-tree --no-commit-id --name-only -r $CI_COMMIT_SHA | xargs -n 1 dirname | uniq # command 1
   for i in $(find . -name "terragrunt.hcl" -print0 | xargs -0 git diff-tree --no-commit-id --name-only -r $CI_COMMIT_SHA | xargs -n 1 dirname | uniq); do cd /usr/bin/regula/bin && ./regula /path/to/$i /usr/bin/regula/lib /path/to/custom-rules; done # command 2
else 
   :
fi

这是错误:

$ ./compliance_check.sh
dirname: missing operand
Try 'dirname --help' for more information.
dirname: missing operand
Try 'dirname --help' for more information.
Cleaning up file based variables
00:01
Job succeeded

请帮忙!!!

标签: bashgitlab-ci

解决方案


如果您不想使用空参数列表xargs运行dirname,并且它是 GNU 版本,请执行以下操作:

xargs --no-run-if-empty -n 1 dirname

...对于那个管道元素。

(另外,考虑使用-d $'\n'来抑制 xargs 在您不使用时开箱即用的一些更不幸的行为-0)。


减少重复工作的替代实现可能看起来有点像下面的代码(完全未经测试,因为问题使用了其他人无法访问/测试的工具和目录结构):

#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-3].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac

declare -A dirnames=( )
readarray -d '' -t targetFiles < <(find . -name "terragrunt.hcl" -print0)
for file in "${targetFiles[@]}"; do
  readarray -t changedFileNames < <(
    git diff-tree --no-commit-id --name-only -r "$CI_COMMIT_SHA" "$file"
  )
  for changedFileName in "${changedFileNames[@]}"; do
    dirnames[${changedFileName%/*}]=1
  done
done
for dirname in "${!dirnames[@]}"; do
  (cd /usr/bin/regula/bin && exec ./regula /path/to/"$dirname" /usr/bin/regula/lib /path/to/custom-rules)
done

推荐阅读