Bash Question

Recursively list files from a given directory in Bash

I know that it can be done using

ls -R path
. But I'm trying to learn the syntaxis and another control structures in the language, so I'm trying to write my own code:



lsRec() {
for x in $1*; do
if [ -d "$x" ]; then
lsRec $x;
echo "$x";

lsRec $arg;

When I call the command
./ ~/Documents/
, the terminal throws:
segmentation fault (core dumped)
. Why I'm getting this error?, Am I missing something in my code?


Answer Source

Your algorithm is entering endless loop since lsRec function implicitly expects its argument to end in "/". First level works, as you pass path ending with "/" as input, but second level doesn't, as the path you're making recursive call with doesn't end in "/". What you could do is either add the slash when you make a recursive call, so it'll look like lsRec $x/, or (better yet) add the slash in the loop arguments as in for x in $1/*; do (as system generally ignores multiple consequent path separators).

Moving forward, I'd advise you to quote the values (e.g. lsRec "$x", lsRec "$arg") to avoid issues when path contains whitespace characters; and also using something like ls "$1" | while read x; do ...; done (just an example, one could do this better) instead of for x in $1* for the very same reason. You'll get there when you create a directory with space in its name under directory hierarchy you're scanning.