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:

#!/bin/sh

arg=$1;

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

lsRec $arg;


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

Thanks.

Answer

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.