2017-08-21 75 views
0

我將遞歸運行數據的基本目錄,然後修改其中的每個文件,並在另一個基本目錄上創建一個新文件。所以我需要兩個參數,一個是原始數據庫目錄的路徑,另一個是用於放入新文件的基礎目錄,但是我的代碼有問題。當我將這兩個參數放在主函數下時,而不是在終端上輸入它們。希望有人能幫助我。爲什麼這個bash腳本不能遞歸運行?

以下是我的代碼:


function traverse() { 
    for file in $(ls "${data_path}") 
    do 
     echo "in file: ${data_path}/${file}" 
     if [[ ! -d ${data_path}/${file} ]]; then 

      if [[ ${data_path}/${file} == *.nii.gz ]];then 

       echo "is nifti: ${data_path}/${file} " 

      else 
     echo "not file" 
     echo ${data_path} 

     temp_path=${data_path/'/data2/Projects/Incoming_monkey'/} 
     new_path="${new_destination}/${temp_path}" 
     mkdir -p ${new_path} 
     echo ${new_path} 
     fi 
     else 
      echo "entering recursion with: ${data_path}/${file}" 
      traverse "${data_path}/${file}" "${new_destination}" 
     fi 
    done 
} 
function main() { 

    echo "main start" 

    data_path=/data2/Projects/Incoming_monkey/MAJOM/08_20170706/func 
    new_destination=/data2/Projects/reorientation 

    traverse "${data_path}" "${new_destination}" 
} 

main 

+1

用四個空格前綴代碼/數據。請看[編輯幫助](http://stackoverflow.com/editing-help)。 – Cyrus

+1

全局變量有種挫敗遞歸的思想。 –

回答

0

我沒有試圖說服代碼背後的邏輯,但我可以看到一些明顯的錯誤。在主函數中創建的變量data_pathnew_destination具有全局意義,這就是爲什麼您可以在traverse函數中讀取它們的原因。爲了解決這個問題,我在他們之前添加了declare關鍵字,以便在主要功能的本地。另外,您將這兩個變量作爲參數傳遞給traverse函數,該函數從代碼中不讀取任何這些參數。爲了解決這個問題,我用$ 1和$ 2替換了變量名稱,將其作爲參數讀取。

編輯:發現更多的變量,需要是本地的。 (temp_pathnew_path

#!/bin/bash 

function traverse() { 
    for file in $(ls "${1}") # Replace data_path with 1 
    do 
     echo "in file: ${1}/${file}" 
     if [[ ! -d ${1}/${file} ]]; then 

      if [[ ${1}/${file} == *.nii.gz ]];then 

       echo "is nifti: ${1}/${file} " 

      else 
     echo "not file" 
     echo ${1} 

     declare temp_path=${1/'/data2/Projects/Incoming_monkey'/} 
     declare new_path="${2}/${temp_path}" # Replaced new_destination by 2 
     mkdir -p ${new_path} 
     echo ${new_path} 
     fi 
     else 
      echo "entering recursion with: ${1}/${file}" 
      traverse "${1}/${file}" "${2}" 
     fi 
    done 
} 
function main() { 

    echo "main start" 

    declare data_path=/data2/Projects/Incoming_monkey/MAJOM/08_20170706/func 
    declare new_destination=/data2/Projects/reorientation 

    traverse "${data_path}" "${new_destination}" 
} 

main 
+2

如果你打算髮佈一個答案,請不要在$(ls ...);'中永久使用'for file。 – chepner

+0

我發現'本地'更清楚地表明一個變量具有局部範圍。 –

相關問題