2014-07-03 54 views
1

我有此腳本在bash塔哈特應檢查如果USB設備存在於機器,如果不是,那麼重新啓動它:bash腳本的USB記憶棒後重新啓動被拔掉

#!/bin/bash 

UNPLUG_MESSAGE="PLEASE UNPLUG THE USB STICK NOW" 
export REMOVABLE_DRIVE="" 

function dev_detect { 
    for _device in /sys/block/*/device; do 
     if echo $(readlink -f $_device)|egrep -q "usb"; then 
     _disk=`echo $_device | cut -f4 -d/` 
     REMOVABLE_DRIVE="$_disk" 
    echo "dev_detect_function" 
    fi 
done 
} 

dev_detect 

clear 

echo $UNPLUG_MESSAGE 

sleep 5 


function check_usb { 
    if [[ $REMOVABLE_DRIVE == *sdb* ]] || [[ $REMOVABLE_DRIVE == *sdc* ]] 
    then 
    dev_detect 
    echo $REMOVABLE_DRIVE 
    echo "PLEASE UNPLUG THE USB STICK"; 
    sleep 2 
    check_usb 
    else 
    echo "else reboot block" 
    sudo reboot 
    fi 
} 


check_usb 

但當我拔下USB隨身碟它檢測到USB :( - 在這裏我犯的錯誤

+1

你也可以在'/ var/log/messages'或直接在'dmesg'的'grep'輸出'grep' USB disconnect''。你會得到'usb 2-1.6:USB斷開連接,設備號碼101' –

回答

2

我會寫不同的是:

#! /bin/bash 

REMOVABLE_DEVICE=$(find /sys/block/ -type l -printf "%f %l\n" | awk '/usb/{print $1}') 

if grep -Eq "(sdb|sdc)" <<< "$REMOVABLE_DEVICE" ;then 
    echo "DEVICE IS PRESENT!" 
else 
    echo "DEVICE NOT PRESENT!" 
fi 
  1. 使用find更有效,所以你不需要使用readlink 也不grep
  2. 使用awk更有效,所以你不需要使用grep也不 cut

我發佈之前測試這個腳本,我希望它可以幫助:)