Pregunta

This function loops through the folder names within destinationDirectory to find the highest numerical value on the end of the filename, increments that value, and appends the value to the end of the folderNameWithoutNumber. Or I thought it would. The bash function:

$backupFolderNumber=0
$1=$sourceDirectory
$2=$destinationDirectory
$3=$folderNameWithoutNumber
# The values when the function are called

backupDirectory() {
for currentFolder in $2/*
do
    backupFolderNumber=$(echo $currentFolder | tr -cd '[[:digit:]]')
done
let backupFolderNumber+=1
cp -r $1 $2/$3$backupFolderNumber
echo "Backup complete."
}

When this function is called the first 10 times, everything seems to work fine, as in I get the first ten backups created in the form of /path/to/backups/folderName_1, /path/to/backups/folderName_2, ... /path/to/backups/folderName_10. When the function is called again, /path/to/backups/folderName_11 is not created.

My first question is why is this not working the way I thought it would (creating folderName_11 and counting)?

My second question is how would I format the filename to include preceeding zeros to make the numerical part 3 digits long (folderName_001, folderName_002)?

My third and final question, the destination should only ever contain backups of the same folder under the same name, so the last folder in the group should have the most recent (highest) number. What can be done to guarantee the highest number is found if for some reason the folder was out of sorted order?

¿Fue útil?

Solución

Bash has a printf function which can help you answer your second question.

If your backupFolderNumber is an integer you can use:

paddedFolderNumber=$(printf "%03d" $backupFolderNumber)

The %03d syntax tells printf to print the number as being at least three characters long, padding with zeros if the backupFolderNumber is fewer then three characters in length.

Note that if you have folders with names of the form folder_name001 your current code,

backupFolderNumber=$(echo $currentFolder | tr -cd '[[:digit:]]')

will no longer give you your desired results, as it will return i.e 010 which the let statement will think is octal for 8, resulting in backupFolderNumber becomming 9, not 11 or 011 as you would want.

One solution to give you the non-padded number when retrieving the number from the current folder names is:

backupFolderNumber=$(echo $currentFolder | tr -cd '[[:digit:]]' | sed -e 's/^0\{1,2\}//')

Here sed strips away 1 or 2 leading zeros (this way the sequence 000 returns 0 not nothing), hence let should expect a decimal not an octal.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top