2012年1月4日 星期三

[Linux] Auto copy USB video file to HD

需求插入USB後自動尋找相關檔案並copy到指定資料夾
試了兩種方式

先利用先前文章介紹的udev,register一個callback,我們先以 root 的權限在 /etc/udev/rules.d/ 這個資料夾裡建立一個新檔:
  1. $ sudo vim /etc/udev/rules.d/z101_run_my_script.rules
    檔案內容只要一行:
    RUN+="/home/copy_file
當每次USB插入時event就會產生

1. 搜尋法
  1. #!/bin/bash
    # Shell to read source file and copy it to target file. If the file
    # is copied successfully then give message 'File copied successfully'
    # else give message 'problem copying file'
    # --------------------------------------------------------------
    LOGFILE=/home/nash/copy_file.log #定義變數LOGFILE
    exec 3>> $LOGFILE && exec >& 3 && exec 2>&1 #把stdout/stderr導入$LOGFILE
    
    count=1
    
    if [ "$SUBSYSTEM" = "usb_device" -a "$ACTION" = "add" ]
    then
      while [ "$n" -lt 10 ]
      do
        for file in /media/*/aaa.wmv
        do
          echo $file
        done
    
        count=$(( $count + 1 ))
        echo $n
    
        if [ -e $file ]
        then
          break
        fi
    
        sleep 1
      done
    
      if [ -e $file ]
      then
         echo "NEW video File exists"
         if [ -e /home/nash/aaa.wmv ]
         then
            echo "old video File exist"
            rm -fr /home/nash/aaa.wmv
         fi
    
         # copy file
         cp $file /home/nash/aaa.wmv
    
         # store exit status of above cp command. It is use to
         # determine  if shell command operations is successful or not
         status=$?
    
         if [ $status -eq 0 ]
         then
           echo 'File copied successfully'
           exit 0
         else
           echo 'Problem copuing file'
           exit 1
         fi 
      fi
    
      echo "NEW video File does not exists"
    fi
2. 強制法[暴力法]
一.先在/mnt下建立兩個資料夾
  1. [root@ ~]# mkdir mnt/sda1
    [root@ ~]# mkdir mnt/sdb1
二.不等系統去找USB就先掛載
  1. 
    #!/bin/bash
    # --------------------------------------------------------------
    LOGFILE=/home/nash/copy_file.log #定義變數LOGFILE
    exec 3>> $LOGFILE && exec >& 3 && exec 2>&1 #把stdout/stderr導入$LOGFILE
    
    #掛載USB
    mount /dev/sda1 /mnt/sda1
    mount /dev/sdb1 /mnt/sdb1
    
    #拷貝檔案
    cp /mnt/sda1/aaa.wmv /home/nash/aaa.wmv
    cp /mnt/sdb1/aaa.wmv /home/nash/aaa.wmv
    
    #同步
    sync
    
    #移除掛載USB
    umount /dev/sda1
    umount /dev/sdb1

沒有留言:

張貼留言