【发布时间】:2021-04-15 19:21:40
【问题描述】:
我有一个 bash 脚本,它使用 while 循环来获取从 find 命令返回的每个文件的基本名称。我在这里将其简化为一行:
$ while read myFile; do echo $(basename $myFile) ; done <<< $(find ./*test* -maxdepth 1 -type f -exec ls {} + 2>/dev/null)
testRelease.sh
在 find 命令没有结果的情况下,我预计 while 语句的条件不满足,“do”部分被忽略。事实并非如此:
$ while read myFile; do echo $(basename $myFile) ; done <<< $(find ./*noMatch* -maxdepth 1 -type f -exec ls {} + 2>/dev/null)
basename: missing operand
Try `basename --help' for more information.
看起来好像while语句添加了一个条件试图处理的空行:
$ while read myFile; do echo $myFile ; done <<< $(find ./*noMatch* -maxdepth 1 -type f -exec ls {} + 2>/dev/null)
$
独立运行 find 命令时不会出现此空白行。什么是添加这个空行,为什么没有找到结果时while语句会处理它?
【问题讨论】:
-
一如既往,首先通过shellcheck.net 运行它并修复它指出的问题。
-
shopt -s nullglob -
只是想知道:
-exec ls {} +的意义何在? (隐含的)-print不会做同样的工作但速度更快吗? -
@Socowi 好点,谢谢
-
注意,你使用的id
...done < <(find...不会有这个问题。