Shell recursion script

I am learning the Linux command and I am practicing and trying to write a basic shell script that lists 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 it because the shell does not allow recursion? please help, thanks!

+4
source share
2 answers

The shell certainly supports recursion. But your function takes arguments, and you pass it stdin. Also, you really don't have to parse ls output . 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 will have to rewrite listit to do this. This is difficult because you only get one standard input, and every recursive call will try to own it. File names are a simple thing available as arguments across the globe, so I will stick with this.

+2
source

You overflowed the stack with infinite recursion. Consider the call to listit / .

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

See this answer for the next event .

+2
source

Source: https://habr.com/ru/post/1483411/


All Articles