|
Needs Expansion |
#title Recursive Maintenance Scripts
Introduction
Shell scripts can be one of the most useful tools for maintaining a Linux system. Here we'll give some simple examples of a recursive script that can be used to perform maintenance functions on an entire directory structure.
Basic structure
The basic structure of the recursive script uses a function call which in turn calls itself whenever it finds a directory. The script is run with a parameter of one or more directory names. For example:
username@systemname:~$ myscript.sh directory_name_to_process another_directory_to_process
# the function to perform function recursivefunction() { # for every file in the directory - do something with it for file in "$1"/*; do # do something done # once you've processed all the files go back and check for directories for file in "$1"/*; do # if you find a directory... if [ -d "$file" ]; then # perhaps do something # then call the function again with this new directory recursivefunction "$file" fi done } for param in "$@"; do recursivefunction "$param" done
Examples
Correcting file permissions
Have you ever copied a directory structure from a CDROM or USB thumb drive and the file and directory permissions were a mess? This quick script can recurse through the directory structure and set some sane permissions.
function setperms() { for file in "$1"/*; do chmod 664 "$file" done for file in "$1"/*; do if [ -d "$file" ]; then chmod 775 "$file" setperms "$file" fi done } for param in "$@"; do setperms "$param" done
Convert all video files
Want to convert all your various video files to the open standard Ogg Theora format?
function converttoogg() { for file in "$1"/*.mpg; do chmod 660 "$file" ffmpeg2theora -v 10 -a 10 "$file" done for file in "$1"/*.avi; do chmod 660 "$file" ffmpeg2theora -v 10 -a 10 "$file" done for file in "$1"/*.vob; do chmod 660 "$file" ffmpeg2theora -v 10 -a 10 "$file" done for file in "$1"/*.wmv; do chmod 660 "$file" ffmpeg2theora -v 10 -a 10 "$file" done for file in "$1"/*.mov; do chmod 660 "$file" ffmpeg2theora -v 10 -a 10 "$file" done for file in "$1"/*; do if [ -d "$file" ]; then chmod 770 "$file" converttoogg "$file" fi done } for param in "$@"; do converttoogg "$param" done