Sysadmin Diaries - Day 24
Tip of the day?Seems to be turning into script of the day.Yes another script. This time I wanted a script to rename file, file.txt to file.txt.old orĀ file,txt.new to file.txt. Hereās the script to do this.
#!/bin/bash # Rename files depending on input # Check input is valid i.e. one argument either old or new if [ $# -ne 1 ] then echo "Usage: $0 new | old" exit 1 else if [[ $1 != "new" && $1 != "old" ]] then echo "Usage: $0 new | old" exit 1 fi fi TYPE=$1 # backup file to file.old if [ $TYPE = "old" ] then find . -name "*.txt" | while read TXTFILE do mv $TXTFILE ${TXTFILE}.old done fi # Rename file.new to file if [ $TYPE = "new" ] then find . -name "*.new" | while read NEWFILE do NEWNAME=`echo $NEWFILE | cut -d "." -f1-3` mv $NEWFILE $NEWNAME done fi
The script renames the file depending on whether old or new is specified as an argument. The first part just checks if one argument is supplied and if it does, then whether it is old or new. If one of them is an argument, itāll either copy or rename the file depending on the option.
So, in essence, an example of checking input then doing a simple copy/rename,
Until next week

















