2014年3月14日 星期五

 #!/bin/bash
# Must be at least version 4 to have associative arrays
#check if $1 exists
if [ ! -e "$1" ]; then
echo "[error] \"$1\" is not found. terminated"
exit 1
fi

#check if student_photo exists
if [ ! -d student_photo ]; then
echo "[error] \"student_photo/\" not found. terminated"
exit 2
fi

#move the files, creating directory if necessary
while read line
do
 #commented echo "[$line]"
 ary=($line)
 # associative array sid
 declare -A sid

 # check existance in associative array
 if [ ${sid[${ary[1]}]+_} ]; then 
  echo "[Error] Duplicate sid ${ary[1]}. no changes will be done"
  exit 1
 else 
  sid["${ary[1]}"]=1
 fi

done < $1


#move the files, creating directory if necessary
while read line
do
 #commented echo "[$line]"
 ary=($line)
 printf "\"%s\" to \"%s(%s)\"..." ${ary[0]} ${ary[1]} ${ary[2]}
 #echo "\"${ary[0]}\" to \"${ary[1]}(${ary[2]})\""
  #DSC00XX.jpg  05432198 1234
 
 if ! [ -e "student_photo/${ary[0]}" ]; then
  printf "\n[error] \"%s\" is not found or is duplicated. skipped\n" ${ary[0]}

 elif ! [[ ${ary[1]} =~ ^[0-9]{8}$ ]]; then
  printf "\n[error] \"%s\" is not a valid student number (8 digits). skipped\n" ${ary[1]}

 elif ! [[ ${ary[2]} =~ ^[0-9]{4}$ ]]; then
  printf "\n[error] \"%s\" is not a valid programme code (4 digits). skipped\n" ${ary[2]}

 else
  if [ ! -d "student_photo/${ary[2]}" ]; then
   mkdir "student_photo/${ary[2]}"
   printf "\ncreated folder: %s\n" ${ary[2]}
  fi
  if [ ! -e "student_photo/${ary[2]}/${ary[1]}" ]; then
   mv "student_photo/${ary[0]}" "student_photo/${ary[2]}/${ary[1]}.jpg"
  fi
  printf "done\n"
 fi
 #echo ---

done < $1


沒有留言:

張貼留言