Mar*_*iek 139 linux bash mount
检查卷是否安装在 Bash 脚本中的最佳方法是什么?
我真正想要的是一种可以像这样使用的方法:
if <something is mounted at /mnt/foo>
then
<Do some stuff>
else
<Do some different stuff>
fi
Run Code Online (Sandbox Code Playgroud)
Dan*_*ley 162
避免使用,/etc/mtab因为它可能不一致。
避免管道,mount因为它不需要那么复杂。
简单地:
if grep -qs '/mnt/foo ' /proc/mounts; then
echo "It's mounted."
else
echo "It's not mounted."
fi
Run Code Online (Sandbox Code Playgroud)
(后面的空格/mnt/foo是为了避免匹配,例如/mnt/foo-bar。)
小智 88
if mountpoint -q /mnt/foo
then
echo "mounted"
else
echo "not mounted"
fi
Run Code Online (Sandbox Code Playgroud)
或者
mountpoint -q /mnt/foo && echo "mounted" || echo "not mounted"
Run Code Online (Sandbox Code Playgroud)
Ell*_*iew 35
findmnt -rno SOURCE,TARGET "$1"避免了其他答案中的所有问题。它只用一个命令就干净利落地完成了这项工作。
其他方法有以下缺点:
grep -q并且grep -s是一个额外的不必要的步骤,并非所有地方都支持。/proc/\*并非所有地方都支持。(mountpoint也基于 proc)。mountinfo 基于 /proc/..cut -f3 -d' ' 弄乱路径名中的空格.. 保留列表模式只是为了向后兼容。
要获得更强大和可定制的输出,请使用findmnt (8),尤其是在您的脚本中。
重击函数:
#These functions return exit codes: 0 = found, 1 = not found
isMounted () { findmnt -rno SOURCE,TARGET "$1" >/dev/null;} #path or device
isDevMounted () { findmnt -rno SOURCE "$1" >/dev/null;} #device only
isPathMounted() { findmnt -rno TARGET "$1" >/dev/null;} #path only
#where: -r = --raw, -n = --noheadings, -o = --output
Run Code Online (Sandbox Code Playgroud)
用法示例:
if isPathMounted "/mnt/foo bar"; #Spaces in path names are ok.
then echo "path is mounted"
else echo "path is not mounted"
fi
if isDevMounted "/dev/sdb4";
then echo "device is mounted"
else echo "device is not mounted"
fi
#Universal:
if isMounted "/mnt/foo bar";
then echo "device is mounted"
else echo "device is not mounted"
fi
if isMounted "/dev/sdb4";
then echo "device is mounted"
else echo "device is not mounted"
fi
Run Code Online (Sandbox Code Playgroud)
像这样的脚本永远不会是可移植的。unix 中的一个肮脏的秘密是只有内核知道什么文件系统在哪里,缺少诸如 /proc(不可移植)之类的东西,它永远不会给你一个直接的答案。
我通常使用 df 来发现子目录的挂载点是什么,以及它在哪个文件系统中。
例如(需要 posix shell,如 ash / AT&T ksh / bash / 等)
case $(df $mount)
in
$(df /)) echo $mount is not mounted ;;
*) echo $mount has a non-root filesystem mounted on it ;;
esac
Run Code Online (Sandbox Code Playgroud)
有点告诉你有用的信息。
以下是我在我的 rsync 备份 cron 作业之一中使用的内容。它会检查 /backup 是否已挂载,如果未挂载,则尝试挂载它(它可能会失败,因为驱动器位于热插拔托架中,甚至可能不存在于系统中)
注意:以下仅适用于 linux,因为它 grep /proc/mounts - 更便携的版本将运行 'mount | grep /backup',如马修的回答..
如果 !grep -q /backup /proc/mounts ; 然后
如果 !挂载/备份;然后
回声“失败”
出口 1
菲
菲
回声“成功了。”
# 在这里做事