简体   繁体   中英

Recursive directory listing in shell without using ls

I am looking for a script that recursively lists all files using export and read link and by not using ls options. I have tried the following code, but it does not fulfill the purpose. Please can you help.

My Code-

#!/bin/bash

for i in `find . -print|cut -d"/" -f2`
do
if [ -d $i ]
then
echo "Hello"
else
cd $i
echo *
fi
done

Here's a simple recursive function which does a directory listing:

list_dir() {
  local i                      # do not use a global variable in our for loop
                               # ...note that 'local' is not POSIX sh, but even ash
                               #    and dash support it.

  [[ -n $1 ]] || set -- .      # if no parameter is passed, default to '.'
  for i in "$1"/*; do          # look at directory contents
    if [ -d "$i" ]; then       # if our content is a directory...
      list_dir "$i"            # ...then recurse.
    else                       # if our content is not a directory...
      echo "Found a file: $i"  # ...then list it.
    fi
  done
}

Alternately, if by "recurse", you just mean that you want the listing to be recursive, and can accept your code not doing any recursion itself:

#!/bin/bash
# ^-- we use non-POSIX features here, so shebang must not be #!/bin/sh

while IFS='' read -r -d '' filename; do
  if [ -f "$filename" ]; then
    echo "Found a file: $filename"
  fi
done < <(find . -print0)

Doing this safely calls for using -print0 , so that names are separated by NULs (the only character which cannot exist in a filename; newlines within names are valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM