2016-11-27 154 views
-1

循環我有一個bash腳本,我想在一個目錄下運行程序,使用一個文件從另一個目錄中輸入猛砸對目錄

有幾個輸入文件,位於幾個不同的目錄,其中的每一個被用作輸入的程序

的一個迭代中的文件是若干文件類型一個(包含.foo)在每個目錄

我的代碼是

cd /path/to/data/ 
for D in *; do 
    # command 1 
    if [ -d "$D" ] 
    then 
     cd /path/to/data 
     # command 2 
     for i in *.foo 
     do 
      # command 3 
     done 
    fi 
done 

當我運行該腳本,輸出如下

# command 1 output 
# command 2 output 
# command 3 output 
# command 2 output 
# command 2 output 
# command 2 output 
# command 2 output 
# command 2 output 
. 
. 
. 

所以腳本做什麼,我希望它究竟做一次,然後似乎

後不遍歷決賽圈爲什麼是這樣?

+1

你改變了目錄,並改變了它不背部?你的代碼不清楚,因爲你使用了兩次'cd/path/to/data /'。 – Cyrus

+0

一般來說,儘量避免在腳本中使用'cd',你可以將自己打結。儘可能構建和使用完整路徑名稱更爲容易。例如:'對於我在/路徑/到/數據/ *。foo'。 – cdarke

+0

這些命令做了什麼? – Jdamian

回答

0

我想你以後「然後」有一個錯字錯誤... 它更有意義的是:

then 
    cd /path/to/data/$D 
    # command 2 

但是,作爲cdarke建議,這是好事,避免在您的腳本中使用CD 。 你可以有相同的結果是這樣的:

for D in /path/to/data; do 
    # command 1 
    if [ -d "$D" ] 
    then 
     # command 2 
     for i in /path/to/data/$D/*.foo 
     do 
      # command 3 
     done 
    fi 
done 

或者你甚至可以使用發現和避免,如果零件(更少的代碼使之加快你的腳本):

for D in $(find /path/to/data -maxdepth 1 -type d) 
# -type d in find get's only directories 
# -maxdepth 1 means current dir. If you remove maxdepth option all subdirs will be found. 
# OR you can increase -maxdepth value to control how deep you want to search inside sub directories.