We do not have to test for individual directory level 'cos if the bottom directory exists, the parent level should exist. Also, mkdir -p will make all the non-existing parent directories. Also, I introduce 'short circurt' && to ensure directory exist before I move the file.
We can also avoid all the repeating code using in extracting yy/mm/dd/hh by using 'set --' and
sed.
sed will change 2 digits with 2 digits + space so that it can put the result back to "set --" to set the positional variables accordingly
This is my contribution, it should work (even on sh)
Code:
for i in *.jpg
do
# yy is $1, mm is $2, dd is $3, hh is $4
set -- `echo $i | sed -e 's/\([0-9][0-9]\)/\1 /g'`
dir="$1/$2/$3/$4"
[ ! -d $dir ] && mkdir -p $dir && mv $i $dir
done