bash - 正确引用 bash 别名定义
问题描述
我尝试将以下命令放入 bash 别名中。该命令本身可以正常工作,但是当我尝试为其设置别名时,出现以下错误:
命令
find . -maxdepth 1 -mindepth 1 -type d -exec sh -c 'echo "$(find "{}" -type f | wc -l)" {}' \; | sort -nr
别名
alias csfiles='find . -maxdepth 1 -mindepth 1 -type d -exec sh -c 'echo "$(find "{}" -type f | wc -l)" {}' \; | sort -nr'
错误:
-sh: alias 0: not found
-sh: alias {} \; | sort nr: not found
我认为这意味着我没有正确使用引号,但我无法确定正确的组合。帮助?
解决方案
你的外层find
没有做任何你不能用简单的 glob 做的事情。这消除了一层引号(以及sh
找到的每个目录的过程)。
# Ignoring the issue of assuming no file name contains a newline
for d in ./*/; do
echo "$(find "$d" -type f | wc -l) $d"
done
只需定义一个 shell 函数来消除对alias
.
csfiles () {
for d in ./*/; do
echo "$(find "$d" -type f | wc -l) $d"
done
}
剩余的调用find
也可以用for
循环替换,消除了每个文件名一行的问题假设:
csfiles () {
for d in ./*/; do
echo "$(for f in "$d"/*; do [ -f "$f" ] && echo; done | wc -l) $d"
done
}
find
如果它支持主文件,则可以保留-printf
,因为您不关心文件的实际名称,只需要每个文件获得一行输出即可。
csfiles () {
for d in ./*/; do
echo "$(find "$d" -type f -printf . | wc -l) $d"
done
}
推荐阅读
- angular - 在 ng-sidebar 中显示 nb-datepicker
- deep-learning - 在 Keras 2.0 中使用合并
- ios - 从 Xcode 导出 IPA 以使用另一个分发证书重新签名
- javascript - 为什么 json 可以轻松导入而 csv 在 Nodejs Typescript javascript 中无法导入?
- python - 无法在 python 3.7 中导入本地化库
- c# - 在 C# 中将文件从 FTP 直接传输到 Azure Blob 存储
- javascript - 为什么我的阶乘函数返回 NaN?
- webassembly - 如何在 webassembly 中编码图像,如 base64
- mysql - 时间格式问题:比较不起作用
- c# - 使用 TreeInstance 将树添加到地形 C#