'Looping through all files in a directory [duplicate]

I want to write a shell script that will loop through all the files in a directory and echo "put ${filename}". Can anyone point me in the right direction?



Solution 1:[1]

For files and directories, not recursive

for filename in *; do echo "put ${filename}"; done

For files only (excludes folders), not recursive

for file in *; do 
    if [ -f "$file" ]; then 
        echo "$file" 
    fi 
done

For a recursive solution, see Bennet Yee's answer.

Solution 2:[2]

Recursively (including files in subdirectories)

find YOUR_DIR -type f -exec echo "put {}" \;

Non-recursively (only files in that directory)

find YOUR_DIR -maxdepth 1 -type f -exec echo "put {}" \;

Use * instead of YOUR_DIR to search the current directory

Solution 3:[3]

For all folders and files in the current directory

for file in *; do
    echo "put $file"
done

Or, if you want to include subdirectories and files only:

find . -type f -exec echo put {} \;

If you want to include the folders themselves, take out the -type f part.

Solution 4:[4]

If you don't have any files, then instead of printing * we can do this.

format=*.txt
for i in $format;
do
 if [[ "$i" == "$format" ]]
 then
    echo "No Files"
 else
    echo "file name $i"
 fi
done

Solution 5:[5]

One more alternative using ls and sed:

$ ls -1 <dir> | sed -e 's/^/put /'

and using ls and xargs:

$ ls -1 <dir> | xargs -n1 -i%f echo 'put %f'

Solution 6:[6]

this will work also recursively if you have any sub directories and files inside them:

find . -type f|awk -F"/" '{print "put ",$NF}'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ThisClark
Solution 2 winklerrr
Solution 3 ThisClark
Solution 4
Solution 5
Solution 6 Vijay