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

后端 未结 2 1490
情话喂你
情话喂你 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
    

提交回复
热议问题