How is the logic, efficiency and can it be improved?
This is a snippet from my .bashrc
file, I just wrote it.
The code is supposed to do this:
Backup my .bash_history
file if it is 1000 lines or less from the defined size of HISTSIZE=100000
and HISTFILESIZE=100000
lines, then backup the file.
- Check if
.bash_history
is 99000 lines or more. - Check if
~/.bash_history.old
exists if it doesn't use that filename. - Increment
i
one digit larger than is already used by filenames.(filename-4.old) - Check if there are more than 20 files already backed up and warn if it is.
- Set the new filename into a variable.
- Check if the last file with a digit in it's filename is older than the original.
cp
the file tonew_name
Here is the code:
# Count the number of lines in `/.bash_history and check if it's equal or more than a thousand
if (( $(wc -l < ~/.bash_history) >= 99000 ))
then
name=~/.bash_history
# Here is the suffix of the new files and the ones I check for
old=.old
# -e FILE ==> True if FILE exists.
if [[ ! -e ~/.bash_history.old ]]
then
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
# Here I copy $name which is ~/.bash_history and create backup file
cp $name ~/.bash_history.old
else
# i is the increment in the filenames to be checked and created
i=0
# $name$old is ~/.bash_history.old
if [[ -e $name$old ]]
then
# Here I count how many copies there are with digits in the filename
while [[ -e "$name-$i$old" ]]
do
let i++
done
fi
# if there are 20 files already backed up then I need to archive them somewhere else
if [[ "$i" -ge 20 ]]
then
printf "%s\n" "********************************************************" "You need to arhive your history files they are mounting up!!!" "**************************************************************"
fi
new_name=$name-$i$old
minus=$(( i - 1 ))
if [ $name -nt "$name-$minus$old" ]
then
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
cp ~/.bash_history "$new_name"
fi
fi
fi
This is the result from shellcheck.net
:
Line 16:
let i++
^-- SC2219: Instead of 'let expr', prefer (( expr )) .