首页 > 解决方案 > 正确引用 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

我认为这意味着我没有正确使用引号,但我无法确定正确的组合。帮助?

标签: bashalias

解决方案


你的外层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
}

推荐阅读