bash how to loop through files

Answer

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/sample.sh
touch /root/test/example.sh
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.."
done

Output: Processing /root/test/example.sh file.. Processing /root/test/sample.sh 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 "$*"
do
echo "Processing $FILE" file.

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

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.