bash how to loop through files


You can use for loop. Here is syntax: for ELEMENT in $ARRAY; do command; done

Let's try in in live example. First, create a new directory:

mkdir /root/test
cd /root/test
touch /root/test/
touch /root/test/
touch /root/test/document.doc

Secondly, we process all files that has suffix .sh with for loop:

for FILE in /root/test/*.sh
do echo "Processing ${FILE} file.."

Output: Processing /root/test/ file.. Processing /root/test/ file..

Based on the results of output (above), we can see that loop processes all files in the /root/test, which have the suffix .sh

If you want to process command line arguments use:

for FILE in "$*"
echo "Processing $FILE" file.

$* expands to file names of all files in current directory.