0

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.

3
  • try ding - - - while [ read listing; ] do Example - here tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html Commented Apr 2, 2014 at 13:32
  • 3
    @AtulOHolic That's not even close to right. Commented Apr 2, 2014 at 13:36
  • Ohh, my bad. I was only trying to help. Thanks for correcting. :) Commented Apr 2, 2014 at 13:49

1 Answer 1

6

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[@]##*/}
Sign up to request clarification or add additional context in comments.

4 Comments

Is $REPLY the default variable name for the while read? Otherwise I don't understand it.
Apparently so @fedorqui (tldp.org/LDP/abs/html/internalvariables.html) - I learned something new too :)
Note that while read; do ...; done < <(find "$PWD") is often written find . | while read ..., with the side effect of the while loop running in a subshell.
Not only is using REPLY less typing by itself, but the entire line (including trailing and leading whitespace) is included.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.