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

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

Leave a Comment