如何使用 bash 中的 if 语句检查 USB 设备

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8714717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:14:44  来源:igfitidea点击:

How to check for usb device with if statement in bash

bash

提问by suffa

I'm attempting to create an automated bash script that fills up a file with urandom in the unit's flash storage. I can manually use all of the commands to make this happen, but I'm trying to create a script and having difficulty figuring out how to check for the usb device. I know that it will be either sda1 or sdb1, but not sure if the code below is sufficient ...? Thanks! Below, is the code:

我正在尝试创建一个自动 bash 脚本,该脚本在单元的闪存中用 urandom 填充文件。我可以手动使用所有命令来实现这一点,但是我正在尝试创建一个脚本并且很难弄清楚如何检查 USB 设备。我知道它将是 sda1 或 sdb1,但不确定下面的代码是否足够......?谢谢!下面,是代码:

if /dev/sda1
then
         mount -t vfat /dev/sda1 /media/usbkey
else
         mount -t vfat /dev/sdb1 /media/usbkey
fi

回答by Diego Torres Milano

You can mount by labelor UUIDand hence reduce the complexity of your script. For example if your flash storage has label MYLABEL(you can set and display VFAT labels using mtools' mlabel):

您可以通过标签UUID挂载,从而降低脚本的复杂性。例如,如果您的闪存存储有标签MYLABEL(您可以使用mtools的 mlabel设置和显示 VFAT 标签):

$ sudo mount LABEL=MYLABEL /media/usbkey

回答by Matt H

The way I script mountable drives is to first put a file on the drive, e.g. "Iamthemountabledrive.txt", then check for the existence of that file. If it isn't there, then I mount the drive. I use this technique to make sure an audio server is mounted for a 5 radio station network, checking every minute in case there is a network interrupt event.

我编写可安装驱动器脚本的方法是首先在驱动器上放置一个文件,例如“Iamthemountabledrive.txt”,然后检查该文件是否存在。如果它不存在,那么我安装驱动器。我使用这种技术来确保为 5 个广播电台网络安装了音频服务器,每分钟检查一次,以防出现网络中断事件。

testfile="/dev/usbdrive/Iamthedrive.txt"
if [ -e "$testfile" ]
then
  echo "drive is mounted."
fi