I know that it can be done using ls -R path
. But I'm trying to learn the syntax and control structures of the shell 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.
The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.
Using Find You can also use the find command followed by the target directory and the file you wish to locate. The command will start in the root directory and recursively search all the subdirectories and locate any file with the specified name.
To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.
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 adjacent path separators).
Moving forward, I'd advise you to quote the values (e.g. for x in "$1/"*
, lsRec "$x"
, lsRec "$arg"
) to avoid issues when path contains whitespace characters. You'll get there when you create a directory with space in its name under directory hierarchy you're scanning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With