recursion in shell script
Solution 1
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.
Solution 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.
Mike Lee
Updated on June 08, 2022Comments
-
Mike Lee almost 2 years
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!
-
kojiro almost 11 yearsParentheses aren't correct syntax for function applications in shell.
-bash: syntax error near unexpected token '/'