【问题标题】:getting filenames from directory in shell script从shell脚本中的目录获取文件名
【发布时间】:2015-05-24 15:20:06
【问题描述】:

我想使用 shell 脚本对目录中存在的所有文件进行循环。此外,我想显示每个文件的内容。我将目录作为命令行参数传递。

我有一个简单的循环如下:

for file in $1
do
    cat $file
done

如果我跑步

sh script.sh test

其中 test 是一个目录,我只获取第一个文件的内容。

有人可以帮我吗?

【问题讨论】:

标签: linux shell unix


【解决方案1】:

几个选择:

SMA 代码的紧凑修改:

for file in $1/*
 do
      [[ -f $file ]] && cat $file
 done

或使用查找:

find $1 -type f -exec cat \{\} \;

【讨论】:

  • 但是,我只需要文件名。在这里,我也得到了父目录的文件名。例如如果我的文件在测试目录中,那么我得到的文件名是“test/file.txt”。如何只获取“file.txt”
  • 其实我在找name=$(basename "$file"),不过谢谢。
【解决方案2】:

尝试类似:

 for file in $1/*
 do
     if [[ -f $file ]] ##you could add -r to check if you have read permission for file or not
     then
         cat $file
     fi
 done

【讨论】: