This script does what you want (based on reply from codeforester):
curmonth=$(date +%Y%m)
for filename in ????????-???.jpg; do
filemonth=${filename:0:6}
[ $curmonth = $filemonth ] && continue;
[ ! -d $curmonth ] && mkdir $curmonth
if [ ! -d $curmonth/. ]; then
echo "$0: error: Can not create directory $curmonth"
break
fi
mv $filename $curmonth
done
- A variable holds current year month.
- All the files with the "????????-??.jpg" pattern are examined.
- The month in the filename is extracted.
- If the month of the file equals the current one, skip
- If doesn't exist the destination directory, create it
- ENSURE the destination directory is there, otherwise mv turns destructive
- Finally move the file
There is a bug in this code: if it happens that a destination directory, like "201702", already exists but it is not writable, then the mv
will fail. If the directory does not exist, then it is created, and it is assumed that a directory just created is writable (normally it is... are we 100% sure?) :-)