平常電源都是關閉,只有要傳資料時才會開啟,但每次都要 sudo mount ,接著在不同目錄內找新資料傳過去,實在很麻煩,這時想到可以利用 rsync 來同步資料夾,不用自己比對,想說這麼簡單的東西不必再用 Python ,練習寫個 shell script 就行了,沒想到也是卡了快一天...Orz
作法是在 /etc/fstab 內先將硬碟設定為一般使用者可以 mount ( pass 要設為 0 ,不然一開機就會檢查,然後卡住... )
# get UUID
blkid
# In /etc/fstab, set user, noauto
/dev/disk/by-uuid/a123-456a-789d-abcd /mnt/HDD ext4 rw,user,noauto,suid,dev,exec,async 0 0
sync.sh:
裡面大部份程式碼都是從網路上的範例 copy 過來,應該還有更好的寫法,但可以正常運作就足夠了。
#!/bin/bash
# Description:
# sync multiple folders to external Hard disk
MOUNT_POINT=/mnt/HDD
### array in shell script
SOURCE_DIR=(
/mnt/SOURCE_1/
/mnt/SOURCE_2/
/mnt/SOURCE_3/
)
DEST_DIR=(
/mnt/DEST_1
/mnt/DEST_2
/mnt/DEST_3
)
# check if Hard disk mounted or not
if [[ -z `mount | grep "$MOUNT_POINT"` ]]
then
mount $MOUNT_POINT
echo "mount $MOUNT_POINT "
else
echo "$MOUNT_POINT already mounted !!"
fi
echo
# if unable to mount external Hard disk , stop the script and leave
if [[ -z `mount | grep "$MOUNT_POINT"`]]
then
echo "***** Unable to mount $MOUNT_POINT *****"
exit 1
fi
### seq : like range() in python
### ${#SOURCE_DIR[*]} : total element number in $SOURCE_DIR
# use for loop to sync multiple directories, counter start from 0
for counter in `seq 0 $(( ${#SOURCE_DIR[*]} - 1 ))`
do
echo "*********************************************"
echo "Source:" ${SOURCE_DIR[$counter]}
echo "Dest: " ${DEST_DIR[$counter]}
echo "*********************************************"
echo
rsync -av --exclude="*.sh" ${SOURCE_DIR[$counter]} \
${DEST_DIR[$counter]}
echo
done
exit 0;
令我驚訝的是 shell script 內也有 for ... in ... ( 不好意思,我什麼都不知道 ),命令串接也很好用;但變數存取、運算和陣列相關的操作讓我很想用 python ;一些簡單的東西用 shell script 寫起來應該會很方便,只是目前還不熟...
沒有留言:
張貼留言