5

I am learning Linux command and I am practicing and trying to write a basic shell script which list all the files and files in subfolders, like ls *, using recursion.

#!/bin/bash

# list-all: one command to list them all!!!!

listit () {
        if [ -d "$1" ]
        then
                listit "$1"
        else
                echo "$1"
        fi  
}

ls | while read items; do
        listit "$items"
done

However, the result shows:

./list-all: line 16:  1101 Done                    ls
      1102 Segmentation fault: 11  | while read items; do
    listit "$items";
done

Is that because shell doesn't allow recursion? please help, thank you!

3
  • 1
    +1 to you for your learning efforts. Are you aware of ls -R or find . type -f? Commented May 29, 2013 at 19:26
  • @glennjackman, Thank you! I just realized you can use these commands. Though for the second one, I think it should be find . -type f Commented May 31, 2013 at 15:40
  • Indeed, thanks for spotting the typo Commented May 31, 2013 at 15:41

2 Answers 2

3

The shell certainly supports recursion. But your function takes arguments, and you're passing it stdin. Besides that, you really shouldn't be parsing the output of ls. Consider this:

listit() {
    while [ "$1" ]; do
        if [ -d "$1" ]; then
            listit "$1"/*
        else
            printf '%s\n' "$1"
        fi
        shift
    done
}

listit *

If you really want to read stdin, you'd have to rewrite listit to do that. That's tricky, since you only get one standard input, and each recursive call would try to own it. Filenames are a simple thing accessible as arguments through globbing, so I'd stick to that.

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

Comments

2

You overflowed the stack with an infinite recursion. Consider calling listit /.

The first if will see that / is a directory so it will call listit / which will then call listit / ...

See this answer for what happens next.

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.