shell腳本for循環(huán)實(shí)現(xiàn)文件和目錄遍歷
一個(gè)for循環(huán)實(shí)現(xiàn)一個(gè)目錄下的文件和目錄遍歷,很實(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` #注意此處這是兩個(gè)反引號(hào),表示運(yùn)行系統(tǒng)命令
do
if [ -d $1"/"$file ] #注意此處之間一定要加上空格,否則會(huì)報(bào)錯(cuò)
then
read_dir $1"/"$file
else
echo $1"/"$file#在此處處理文件即可
fi
done
}
#讀取第一個(gè)參數(shù)
read_dir $1
補(bǔ)充:Shell遍歷目標(biāo)目錄和子目錄下的所有文件
1.編寫(xiě)代碼
#!/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 判斷對(duì)象是否存在
- -d 判斷對(duì)象是否存在,并且為目錄
- -f 判斷對(duì)象是否存在,并且為常規(guī)文件
- -L 判斷對(duì)象是否存在,并且為符號(hào)鏈接
- -h 判斷對(duì)象是否存在,并且為軟鏈接
- -s 判斷對(duì)象是否存在,并且長(zhǎng)度不為0
- -r 判斷對(duì)象是否存在,并且可讀
- -w 判斷對(duì)象是否存在,并且可寫(xiě)
- -x 判斷對(duì)象是否存在,并且可執(zhí)行
- -O 判斷對(duì)象是否存在,并且屬于當(dāng)前用戶
- -G 判斷對(duì)象是否存在,并且屬于當(dāng)前用戶組
- -nt 判斷file1是否比f(wàn)ile2新? [ "/data/file1" -nt "/data/file2" ]
- -ot 判斷file1是否比f(wàn)ile2舊? [ "/data/file1" -ot "/data/file2" ]
3.測(cè)試
測(cè)試結(jié)果:打印出來(lái)了目標(biāo)目錄以及子目錄下的所有文件
?
到此這篇關(guān)于shell腳本for循環(huán)實(shí)現(xiàn)文件和目錄遍歷的文章就介紹到這了,更多相關(guān)shell文件和目錄遍歷內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信