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:

for X in "$PWD" *
    if [ -d "$X" ];
        cd "$X"
        echo "$files" >> filesNames.txt

but, I cannot enter sub directories using:

cd "$X"

What is wrong here?


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:


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

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 *