Shell 脚本列出目录中的所有文件
我正在使用以下代码:
#!/bin/bash
for f in $1 ; do
echo $f
done
The aim is to list down all the files in the directory that is passed as an argument to this script. But it's not printing anything. Not sure what could be wrong with this.
I am using the following code :
#!/bin/bash
for f in $1 ; do
echo $f
done
The aim is to list down all the files in the directory that is passed as an argument to this script. But it's not printing anything. Not sure what could be wrong with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个 Shellcheck - 干净的纯 Bash 代码,以实现 评论:
shopt -s dotglob< /code> 使 shell glob 模式匹配以点 (
.
) 开头的名称。 (find
默认情况下会执行此操作。)shopt -s nullglob
会导致 shell glob 模式在没有匹配项时扩展为空,因此循环 glob 模式是安全的。"$1"/*/
) 导致仅匹配目录(包括目录的符号链接)。删除它 (dir=${d%/}
) 部分是为了简洁,但主要是为了使符号链接测试 ([[ -L $dir ]]
) 能够工作。echo
来打印子目录路径。Try this Shellcheck-clean pure Bash code for the "further plan" mentioned in a comment:
shopt -s dotglob
causes shell glob patterns to match names that begin with a dot (.
). (find
does this by default.)shopt -s nullglob
causes shell glob patterns to expand to nothing when nothing matches, so looping over glob patterns is safe."$1"/*/
) causes only directories (including symlinks to directories) to be matched. It's removed (dir=${d%/}
) partly for cleanliness but mostly to enable the test for a symlink ([[ -L $dir ]]
) to work.printf
instead ofecho
to print the subdirectory paths.如果您只需要列出文件而不是目录。 (这部分我不清楚。)
find
是你的朋友。返回:
此外,请运行
man find
。If you only need to list files not directories. (this part is unclear to me.)
find
is your friend.Returns:
Furthermore, please run
man find
.