List files recursively from a given directory in Bash

I know that this can be done using ls -R path. But I'm trying to learn the syntactic 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 provides: segmentation fault (core dumped). Why am I getting this error? Am I missing something in my code?

Thank.

+4
source share
3 answers

, lsRec , "/" . , , "/" , , , , "/" . , , , , lsRec $x/ ( ) , for x in $1/*; do ( ).

, (, for x in "$1/"*, lsRec "$x", lsRec "$arg"), , . , , .

+8

, " x $1 *" $1, ? , . :

  • , x == $1
  • for " x $1/*"

$1 , ? , "" , " ". "" , , .

, "" "hello/*" "hello *".

:

#!/bin/sh

arg=$1;

lsRec() {
    for x in "$1"/*; do
        echo "$x"
        if [ -d "$x" ]; then
            echo "This is a directory:"
            lsRec "$x";
        else
            echo "This is not a directory:"
            echo "$x";
       fi
    done
}

lsRec "$arg";

, !

+4

I think you created a bomb plug. Your code creates infinite recursion.

You must change the code to:

#!/bin/sh
   arg=$1;

   lsRec() {
      for x in $1/*; do
        if [ -d "$x" ]; then
            echo "$x"  ## here you print the line
            lsRec $x; ## here you pass the contents and NOT the line itself
                        ## your programm was passing dirs without processing
                        ## over and over
        else
            echo "$x";
        fi
    done
}

lsRec $arg;
+2
source

Source: https://habr.com/ru/post/1651222/


All Articles