Practical Applications and Examples
Numeric ranges in shell scripts have a wide range of practical applications. Here are a few examples to illustrate their usefulness:
Generating Backup Files
Suppose you want to keep a history of your important files by creating daily backups. You can use a numeric range to generate the backup file names:
for i in {1..7}; do
tar -czf "backup_$i.tar.gz" /path/to/important/files
sleep 86400 ## Wait for 24 hours (86400 seconds)
done
This script will create seven daily backup files named backup_1.tar.gz
, backup_2.tar.gz
, and so on.
Renaming Multiple Files
If you have a set of files with a consistent naming pattern, you can use a numeric range to quickly rename them. For example, to rename files from file1.txt
, file2.txt
, file3.txt
, to document1.txt
, document2.txt
, document3.txt
:
for i in {1..3}; do
mv "file$i.txt" "document$i.txt"
done
Generating Test Data
Numeric ranges can be useful for generating test data, such as a sequence of numbers or dates. This can be helpful when testing your scripts or applications. For instance, to generate a list of dates for the last 7 days:
for i in {0..6}; do
date --date="$i days ago" +"%Y-%m-%d"
done
Output:
2023-04-26
2023-04-25
2023-04-24
2023-04-23
2023-04-22
2023-04-21
2023-04-20
By understanding how to use numeric ranges in shell scripts, you can automate a wide variety of tasks and make your scripts more efficient and versatile. The examples provided here should give you a good starting point for applying this powerful feature in your own shell scripts.