shell腳本for循環(huán)實(shí)現(xiàn)文件和目錄遍歷
一個for循環(huán)實(shí)現(xiàn)一個目錄下的文件和目錄遍歷,很實(shí)用
[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` #注意此處這是兩個反引號,表示運(yùn)行系統(tǒng)命令 do if [ -d $1"/"$file ] #注意此處之間一定要加上空格,否則會報錯 then read_dir $1"/"$file else echo $1"/"$file #在此處處理文件即可 fi done } #讀取第一個參數(shù) read_dir $1
補(bǔ)充:Shell遍歷目標(biāo)目錄和子目錄下的所有文件
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.參數(shù)
- -e 判斷對象是否存在
- -d 判斷對象是否存在,并且為目錄
- -f 判斷對象是否存在,并且為常規(guī)文件
- -L 判斷對象是否存在,并且為符號鏈接
- -h 判斷對象是否存在,并且為軟鏈接
- -s 判斷對象是否存在,并且長度不為0
- -r 判斷對象是否存在,并且可讀
- -w 判斷對象是否存在,并且可寫
- -x 判斷對象是否存在,并且可執(zhí)行
- -O 判斷對象是否存在,并且屬于當(dāng)前用戶
- -G 判斷對象是否存在,并且屬于當(dāng)前用戶組
- -nt 判斷file1是否比file2新? [ "/data/file1" -nt "/data/file2" ]
- -ot 判斷file1是否比file2舊? [ "/data/file1" -ot "/data/file2" ]
3.測試
測試結(jié)果:打印出來了目標(biāo)目錄以及子目錄下的所有文件
?
到此這篇關(guān)于shell腳本for循環(huán)實(shí)現(xiàn)文件和目錄遍歷的文章就介紹到這了,更多相關(guān)shell文件和目錄遍歷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux踢出遠(yuǎn)程登錄用戶命令(總結(jié)篇)
本文給大家總結(jié)了linux踢出遠(yuǎn)程登錄用戶命令,通過linux命令介紹了 tty 踢出登錄的操作方法,本文給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-01-01Shell腳本實(shí)現(xiàn)自動發(fā)送郵件的例子
這篇文章主要介紹了Shell腳本實(shí)現(xiàn)自動發(fā)送郵件的例子,使用.muttrc文件配合shell腳本實(shí)現(xiàn),需要的朋友可以參考下2014-08-08linux上搭建solr的實(shí)現(xiàn)方法(用jetty部署)
下面小編就為大家分享一篇linux上搭建solr的實(shí)現(xiàn)方法(用jetty部署),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12