【发布时间】:2021-02-02 16:28:30
【问题描述】:
我的管道获取terragrunt.hcl 文件的目录并针对它运行一堆测试。如果我的 if 语句为真,我希望我的 bash 执行 2 个命令,如果不是真的跳转到 else 语句,我的 else 应该什么都不做并退出。
下面的这个 bash 确实有效,但是只要不触及terragrunt.hcl,我就会在管道日志中得到这个错误。我假设我的 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
请帮忙!!!
【问题讨论】:
-
顺便说一句,考虑将您的
cd限定为子shell。 f/e,这可能看起来像(cd /usr/bin/regula/bin && exec ./regula /path/to/"$i" /usr/bin/regula/lib /path/to/custom-rules)-exec使用由(创建的子shell,因此不会影响性能,而且您在子shell 中完成了cd的事实意味着它不会t 更改脚本其余部分所在的目录。 -
另外,
for i in $(anything)是错误的形式;见BashPitfalls #1。请参阅Using Find 的“操作”和“复杂操作”部分。并且您可以存储第一个find的输出,因此您无需在if块内重新运行它。乍一看,似乎还有额外的空间可以避免重复工作。 -
...或者,如果您存在该名称下只有一个文件,那么处理该期望被明确打破的情况可能会更好;这样,经过处理程序的代码可以确保假设是正确的。