How to gather the name of the files in each subdirectory into a text file in that subdirectory?

I wanted to save the names of all files in each sub directory into a text file in that sub directory, so I wrote this script:

#!/bin/bash
for X in "$PWD" *
do  
    if [ -d "$X" ];
    then
        cd "$X"
        files="$(ls)"
        echo "$files" >> filesNames.txt
    fi
done

but, I cannot enter sub directories using:

cd "$X"

What is wrong here?

Answer

Per your comments, you only have to descend one level deep. In that case you could use a glob to iterate over directories names and for each dir save file paths in an array, then print the last element of each path to fileNames.txt:

#!/bin/sh

for dir in "$PWD"/*/; do
arr=( "$dir"* )
printf %s\n "${arr[@]##*/}" > "$dir"filesNames.txt
done

To exclude symlinks just add a condition e.g. if [[ ! -L "${dir%?}" ]]; then arr...

Leave a Reply

Your email address will not be published. Required fields are marked *