Looping through files in a directory

Looping through files in a directory is a common task and can be performed in most programming languages. Shell scripting is particularly useful when creating scripts that update all files within a project or even a simple backup script.

// loop through files in a directory files=$(ls /var/www/backups/) for file in $files do // do some stuff done

Sometimes we like to perform our functions on files that are sorted:

// loop through files in a directory and make them sorted files=$(ls /var/www/backups/ | sort) for file in $files do // do some stuff done

Once you know how to perform the above code you'll find it easy to create scripts for your crontab.