Mike Lee
Mike Lee

Reputation: 1215

recursion in shell script

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!

Upvotes: 5

Views: 15696

Answers (2)

kojiro
kojiro

Reputation: 77117

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.

Upvotes: 3

msw
msw

Reputation: 43497

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.

Upvotes: 2

Related Questions