一个for循环实现一个目录下的文件和目录遍历,很实用 [root@localhost shell_order]# cat test27.sh #!/bin/bash #print the directory and
一个for循环实现一个目录下的文件和目录遍历,很实用
[root@localhost shell_order]# cat test27.sh
#!/bin/bash
#print the directory and file
for file in /home/hustyangju/*
do
if [ -d "$file" ]
then
echo "$file is directory"
elif [ -f "$file" ]
then
echo "$file is file"
fi
done
[root@localhost shell_order]# ./test27.sh
/home/hustyangju/array is directory
/home/hustyangju/menuwindow-7.12 is directory
/home/hustyangju/menuwindow-build-desktop is directory
/home/hustyangju/shell_order is directory
[root@localhost shell_order]#
递归遍历
#! /bin/bash
read_dir(){
for file in `ls $1` #注意此处这是两个反引号,表示运行系统命令
do
if [ -d $1"/"$file ] #注意此处之间一定要加上空格,否则会报错
then
read_dir $1"/"$file
else
echo $1"/"$file #在此处处理文件即可
fi
done
}
#读取第一个参数
read_dir $1
1.编写代码
#!/bin/bash
function getdir(){
for element in `ls $fd`
do
dir_or_file=$fd"/"$element
if [ -d $dir_or_file ]
then
getdir $dir_or_file
else
echo $dir_or_file
fi
done
}
root_dir="/opt/datas"
getdir $root_dir
2.参数
3.测试
测试结果:打印出来了目标目录以及子目录下的所有文件
到此这篇关于shell脚本for循环实现文件和目录遍历的文章就介绍到这了,更多相关shell文件和目录遍历内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
--结束END--
本文标题: shell脚本for循环实现文件和目录遍历
本文链接: https://www.lsjlt.com/news/21397.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0