2017-08-21 78 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

我发现'本地'更清楚地表明一个变量具有局部范围。 –

相关问题