插入usb棒后重启的bash脚本

时间:2014-07-03 13:37:33

标签: linux 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 pendrive时,它会检测到usb :( - 我犯了错误?

1 个答案:

答案 0 :(得分: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
  3. 我在发布之前测试了这个脚本,我希望它有所帮助:)