1

My task is create script which lists all subdirs in user's directory and write them in a file.

I created a recursive function which should run through all directories from main and write the names of their subdirs in the file. But the script runs for first folders in my home dirs until reaching the folder without the subfolder. How do I do it correctly?

#!/bin/bash
touch "/home/neo/Desktop/exercise1/backup.txt"
writeFile="/home/neo/Desktop/exercise1/backup.txt"
baseDir="/home/neo"

print(){
    echo $1
    cd $1
    echo "============">>$writeFile
    pwd>>$writeFile
    echo "============">>$writeFile
    ls>>$writeFile
    for f in $("ls -R")
    do
        if [ -d "$f" ]
        then
            print $1"/"$f
        fi
    done
}

print $baseDir
3
  • 1
    This could be a lot easier with the help of find (1) Commented Aug 20, 2020 at 13:07
  • Use the globstar option instead: for d in **/*/; do echo "$f"; done Commented Aug 20, 2020 at 13:20
  • Simply do shopt -s globstar; cd; printf "%s\n" **/. No recursive function needed. Commented Aug 20, 2020 at 13:23

2 Answers 2

2

to get all folders within a path you can simply do:

find /home/neo -type d > /home/neo/Desktop/exercise1/backup.txt

done

Sign up to request clarification or add additional context in comments.

Comments

-1

Try this

fun(){
    [[ -d $1 ]] && cd $1
    echo $PWD
    d=$(echo *)
    [[ -d $d ]] && cd $d || return
    fun
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.