2013-02-26 83 views
1

我期待遍歷使用條件的目錄/ while循環使用在shell腳本循環遍歷目錄結構

情景:路徑是/home/ABCD/apple/ball/car/divider.txt

說我總是從我的程序從/家 我需要從家裏到迭代 - > ABCD - >蘋果 - >球 - >汽車 - > divider.txt

每次我遍歷,檢查獲取的路徑是目錄還是文件,如果文件退出循環並返回路徑 如果返回的路徑是目錄,則循環一次我退出for循環更圓,並繼續..

更新問題

FILES="home" 
for f in $FILES 
do 

    echo "Processing $f" >> "I get ABCD as output 
     if[-d $f] 
    --> returns true, in my next loop, I should get the output as /home/ABCD/apple.. 
     else 
      Break; 
     fi 

done 

後,我應該將/ home/ABCD /蘋果/球/車/作爲輸出

+2

你怎麼知道要循環什麼? – 2013-02-26 04:37:34

+0

我從其他程序得到該文件夾​​的起點,在上面的情況下,我得到輸入爲/ home/ABCD和其他情況下,我可能會得到一個參數爲/ home/example,那麼我需要開始迭代 – gmhk 2013-02-26 04:50:42

+0

您需要迭代*'/ home/ABCD'中的每個*文件? – 2013-02-26 04:51:53

回答

0

這是我已經實現得到它的工作

for names in $(find /tmp/files/ -type f); 
do 
    echo " ${directoryName} -- Directory Name found after find command : names" 

    <== Do your Processing here ==> 

done 

名稱將與完整的文件夾級別

/tmp目錄/文件中的每個文件的方式是我下的文件夾查找文件

+1

如果你有任何帶有空格的文件(或目錄),把$改爲'(find/tmp/files/-type f);'到'find/tmp/files/-type f |同時閱讀名字' – user000001 2013-02-28 10:35:25

0

find /home -type d

會給你/ home下的所有目錄,而不是別的。用您選擇的目錄替換/ home,您將獲得該級別下的目錄。

如果你的心臟被設置在一個檢查每一個文件,你正在尋找if..then測試條件爲:

if [ -f $FILE ] 
then 
echo "this is a regular file" 
else 
echo "this is not a regular file, but it might be a special file, a pipe etc." 
fi 

- 或 -

if [ -d $FILE ] 
then 
echo "this is a directory. Your search should go further" 
else 
echo "this is a file and buck stops here" 
fi 
+0

你的第二個答案看起來不錯,我能夠達到那個水平,如果我發現作爲一個目錄,我需要搜索,那部分我陷入了無法找到任何方式來實現,2)我發現一個更多的觀點是每次我看到子目錄的級別會隨着每個輸入而變化,在我的例子中,我使用了4其他輸入可能爲3級,其他輸入可能爲7級 – gmhk 2013-02-26 08:44:43

2

除了多目的find你可能也想看看tree。它將以樹形格式列出目錄的內容。

$ tree -F /home/ABCD/ 
/home/ABCD/ 
`-- apple/ 
    `-- ball/ 
     `-- car/ 
      `-- divider.txt 

3 directories, 1 file 
+0

我試過樹命令,找不到它的命令錯誤信息 – gmhk 2013-02-26 08:43:33

+0

您可能需要先安裝它,在Debian/Ubuntu'sudo aptitude install tree'。 – Perleone 2013-02-26 09:29:01