如何通过 shell 找到 SDCard 的设备路径

发布于 2023-03-19 22:38:20 字数 2086 浏览 65 评论 0

玩 OrangePi 经常要写镜像到 SD Card 中,每次都手工寻找 SD Card 在 /dev/ 下的设备路径太麻烦,就想着用 shell 脚本来自动寻找。

在网上找了一下,在 https://www.enricozini.org/blog/2019/himblick/locating-a-sd-card/ 上发现了一个 Python 脚本可以自动定位 SD Card 的路径:

def locate(self) -> Dict[str, Any]:
    """
    Locate the SD card to work on

    :returns: the lsblk data structure for the SD device
    """
    res = subprocess.run(["lsblk", "-JOb"], text=True, capture_output=True, check=True)
    res = json.loads(res.stdout)
    devs = []
    for dev in res["blockdevices"]:
        if dev["rm"] and not dev["ro"] and dev["type"] == "disk" and dev["tran"] == "usb":
            devs.append(dev)
            log.info("Found %s: %s %s %s %s",
                     dev["path"], dev["vendor"], dev["model"], dev["serial"],
                     format_gb(int(dev["size"])))
    if not devs:
        raise Fail("No candidate SD cards found")
    if len(devs) > 1:
        raise Fail(f"{len(devs)} SD cards found")
    return devs[0]

大概看了一下,逻辑很简单,就是在 lsblk 的结构中找出 可移动的(rm)、非只读的(ro)、类型为磁盘而不是分区(type)、设备传输类型为usb(tran)的完整设备路径(path). (关于 lsblk 每一列的作用,可以用 lsblk --help 来查看) 感觉完全可以用纯shell来实现,于是花了点时间把它改写成shell脚本

function fail()
{
    echo "$@" >&2
    exit 1
}
function locating_sd_card()
{
    sd_cards="$(lsblk -JOb |jq '.blockdevices[]|select((.rm) and (.ro|not) and (.type == "disk") and (.tran == "usb"))|.path')"
    sd_cards_count="$(echo "${sd_cards}"|wc -l)"
    if [[ ${sd_cards_count} -ne 1 ]];then
        fail "${sd_cards_count} SD CARDS Found!"
    else
        echo "${sd_cards}"
    fi
}

再加上卸载分区和写镜像到 SD 卡的函数,就可以一键重置 OrangePi 了

function umount_sd_card()
{
    lsblk -JOb |jq '.blockdevices[]|select((.rm) and (.ro|not) and (.type == "disk") and (.tran == "usb"))|.children[].mountpoint'|grep -v '[SWAP]'|xargs umount
}

function write_image()
{
    image_file="$1"
    sd_card=$(locating_sd_card)
    umount_sd_card
    dd if="${image_file}" of="${sd_card}" bs=1M
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
26 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文