user3487763
user3487763

Reputation: 31

While loop does not execute

I currently have this code:

listing=$(find "$PWD")
fullnames=""
while read listing;
do
    if [ -f "$listing" ]
        then
            path=`echo "$listing" | awk -F/ '{print $(NF)}'`
            fullnames="$fullnames $path"
            echo $fullnames
    fi 
done

For some reason, this script isn't working, and I think it has something to do with the way that I'm writing the while loop / declaring listing. Basically, the code is supposed to pull out the actual names of the files, i.e. blah.txt, from the find $PWD.

Upvotes: 0

Views: 66

Answers (1)

chepner
chepner

Reputation: 532418

read listing does not read a value from the string listing; it sets the value of listing with a line read from standard input. Try this:

# Ignoring the possibility of file names that contain newlines
while read; do
    [[ -f $REPLY ]] || continue
    path=${REPLY##*/}
    fullnames+=( $path )
    echo "${fullnames[@]}"
done < <( find "$PWD" )

With bash 4 or later, you can simplify this with

shopt -s globstar
for f in **/*; do
    [[ -f $f ]] || continue
    path+=( "$f" )
done
fullnames=${paths[@]##*/}

Upvotes: 6

Related Questions