bash - 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
请帮忙!!!
解决方案
如果您不想使用空参数列表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
推荐阅读
- r - 在 R 中使用 API 并转换为数据帧格式
- python - MemoryError 使用数字范围作为 dict 索引(低效)
- java - 如何使用 JSON 数据在 JavaFX TableView (Scene Builder) 上添加数据
- mysql - 我可以将多个 MySQL 列连接成一列吗?
- r - 查找数据中的所有循环
- javascript - 从 Node.js 获取 PHP 或 Javascript 响应
- vba - 将项目从个人日历移动到接收并自动接受邀请的团队日历?
- ruby - Mac OS Mojave 上的 Ruby 2.4:找不到图像...与 openssl.bundle 相关
- javascript - 运行玩笑测试时出现jsx意外标识符
- python - 尝试使用 USB 将 Nintendo Switch 与 Raspberry 3b+ 通信