Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively list files from a given directory in Bash

Tags:

linux

bash

shell

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.

like image 691
Tomás Juárez Avatar asked Aug 14 '16 19:08

Tomás Juárez


People also ask

How do I get a list of files in a directory and subfolders Linux?

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.

How do I search for files in a folder recursively?

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.

How do you grep all files in a directory recursively for a string?

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.


1 Answers

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.

like image 101
mike.dld Avatar answered Oct 12 '22 21:10

mike.dld