我将尝试使用Shell脚本获取一个目录的内容。
我的脚本如下:
for entry in `ls`; do
echo $entry
done
然而,我的当前目录包含许多文件名中带有空格的文件。在这种情况下,此脚本将失败。
在shell脚本中循环遍历目录内容的正确方法是什么?
PS:我使用bash。
我将尝试使用Shell脚本获取一个目录的内容。
我的脚本如下:
for entry in `ls`; do
echo $entry
done
然而,我的当前目录包含许多文件名中带有空格的文件。在这种情况下,此脚本将失败。
在shell脚本中循环遍历目录内容的正确方法是什么?
PS:我使用bash。
for entry in *
do
echo "$entry"
done
dotglob
选项? - jrharshathshopt -s dotglob
设置了 dotglob
时,*
将匹配以 .
开头的文件。 - Ignacio Vazquez-Abramsls
来解析目录内容,否则会遇到空格问题。应该使用shell扩展代替。 for file in *
do
if [ -f "$file" ];then
echo "$file"
fi
done
ls
。 - ghostdog74