BASH: Writing a Script to Recursively Travel a Directory of N Levels

后端 未结 2 1475
情话喂你
情话喂你 2020-12-03 03:43

I have the following directory structure for example:

/test_dir/d
/test_dir/d/cron
/test_dir/d/cache
/test_dir/d/...(more sub dirs)
/test_dir/tree
/test_dir/         


        
相关标签:
2条回答
  • 2020-12-03 04:21

    Several problems with the script. It should be like this:

    #!/bin/bash
    
    #script to recursively travel a dir of n levels
    
    function traverse() {
    for file in "$1"/*
    do
        if [ ! -d "${file}" ] ; then
            echo "${file} is a file"
        else
            echo "entering recursion with: ${file}"
            traverse "${file}"
        fi
    done
    }
    
    function main() {
        traverse "$1"
    }
    
    main "$1"
    

    However, the correct way to recursively traverse a directory is by using the find command:

    find . -print0 | while IFS= read -r -d '' file
    do 
        echo "$file"
    done
    
    0 讨论(0)
  • 2020-12-03 04:25
    /test_dir/treea is a file
    /test_dir/treeb is a file
    /test_dir/treec is a file
    /test_dir/treed is a file
    

    These are the errors. Some which are not only not directories but do not exist are considered files. I think you need to separate your new files from the directory with slash:

        traverse "${1}/${file}"
    

    And also check that they do exist as well.

    Since you're using bash as well, I'd suggest this form instead:

    #!/bin/bash
    
    shopt -s dotglob  ## Optionally would allow matches for directories beginning with .
    shopt -s nullglob
    
    function traverse {
        local a file
        for a; do
            for file in "$a"/*; do
                if [[ -d $file ]]; then
                    traverse "$file"
                else
                    echo " $file is a file."
                fi
            done
        done
    }
    
    traverse "$@"
    

    You can run the script with multiple arguments.

    A fixed version of your script:

    #!/bin/bash
    
    #script to recursively travel a dir of n levels
    
    function traverse() {   
        for file in $(ls "$1")
        do
            #current=${1}{$file}
            if [[ ! -d ${1}/${file} ]]; then
                echo " ${1}/${file} is a file"
            else
                #echo "entering recursion with: ${1}${file}"
                traverse "${1}/${file}"
            fi
        done
    }
    
    function main() {
        traverse "$1"
    }
    
    main "$1"
    
    0 讨论(0)
提交回复
热议问题