【问题标题】:Is there a way that you can use the "if" branch to check whether a USB stick is connected?有没有办法可以使用“if”分支来检查 U 盘是否已连接?
【发布时间】:2021-10-21 12:05:26
【问题描述】:

有没有一种方法可以使用“if”分支来检查是否连接了 USB-Stick?如果摇杆未连接,则应发出一条消息。

类似:

if [-e /sdb1]
then
cp /home/backup/* /sdb1
rm -r /home/backup/*
echo "your files are successfully transferred."
else
echo "please be sure, if your USB-Stick is connected"
fi

【问题讨论】:

  • [ 是一个命令。 [-e(很可能)不是。您完全有可能定义了一个名为 [-e 的函数,或者您的 PATH 中有一个名为 [-e 的文件,但不太可能。

标签: linux bash shell ubuntu


【解决方案1】:

使用findmnt 实用程序(至少默认安装在 RH 和 Ubuntu 上)

findmnt /backup
echo $?
1

返回 1 表示未安装。

这是一些使用 if 语句的示例代码

findmnt /backup >/dev/null
if [ $? = 0 ]; then
    echo "It's mounted all right"
else
    r=$(( RANDOM % 4 ))
    echo "USB is not mounted."
    case $r in
        0) echo "Check the couch cushions."
           ;;
        1) echo "I think I saw it in the kitchen."
           ;;
        2) echo "Sign up for Prime and get free shipping!"
           ;;
        3) echo "The dog ate it."
           ;;
    esac
fi

【讨论】:

  • if findmnt ...; then ...; else ...; fi更简洁。尽可能避免显式检查$?
【解决方案2】:

不,无论是否连接 USB 设备,挂载点都存在。

像这样应该就足够了:

if [[ $(df | grep "/sdb1") && -d /sdb1 && -w /sdb1 ]]

那是如果,当然,你实际上已经创建了目录/sdb1/

【讨论】:

    猜你喜欢
    • 2011-11-09
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    相关资源
    最近更新 更多