如何在shell脚本中获取目录中的文件列表? [英] How to get the list of files in a directory in a shell script?

查看:158
本文介绍了如何在shell脚本中获取目录中的文件列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 shell 脚本获取目录的内容.

I'm trying to get the contents of a directory using shell script.

我的脚本是:

for entry in `ls $search_dir`; do
    echo $entry
done

其中 $search_dir 是相对路径.但是,$search_dir 包含许多名称中带有空格的文件.在这种情况下,此脚本不会按预期运行.

where $search_dir is a relative path. However, $search_dir contains many files with whitespaces in their names. In that case, this script does not run as expected.

我知道我可以使用 来输入 *,但这仅适用于我当前的目录.

I know I could use for entry in *, but that would only work for my current directory.

我知道我可以切换到那个目录,使用 输入 * 然后再改回来,但我的特殊情况阻止我这样做.

I know I can change to that directory, use for entry in * then change back, but my particular situation prevents me from doing that.

我有两个相对路径 $search_dir$work_dir,我必须同时处理这两个路径,读取它们创建/删除其中的文件等.

I have two relative paths $search_dir and $work_dir, and I have to work on both simultaneously, reading them creating/deleting files in them etc.

那我现在该怎么办?

PS:我使用 bash.

PS: I use bash.

推荐答案

for entry in "$search_dir"/*
do
  echo "$entry"
done

这篇关于如何在shell脚本中获取目录中的文件列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆