[英]Check if directory mounted with bash
我在用
mount -o bind /some/directory/here /foo/bar
我想用 bash 腳本檢查/foo/bar
,看看它是否已安裝? 如果沒有,則調用上面的掛載命令,否則執行其他操作。 我怎樣才能做到這一點?
CentOS 是操作系統。
你懶得提O/S。
Ubuntu Linux 11.10(可能還有最新的 Linux 版本)有mountpoint
命令。
這是我的一台服務器上的示例:
$ mountpoint /oracle
/oracle is a mountpoint
$ mountpoint /bin
/bin is not a mountpoint
實際上,就您而言,您應該可以使用-q
選項,如下所示:
mountpoint -q /foo/bar || mount -o bind /some/directory/here /foo/bar
希望有幫助。
不帶參數運行mount
命令會告訴你當前的掛載。 在 shell 腳本中,您可以使用grep
和 if 語句檢查掛載點:
if mount | grep /mnt/md0 > /dev/null; then
echo "yay"
else
echo "nay"
fi
在我的示例中, if 語句正在檢查grep
的退出代碼,該代碼指示是否存在匹配。 由於我不希望在匹配時顯示輸出,因此我將其重定向到/dev/null
。
mountpoint
的手冊說它:
檢查給定的目錄或文件是否在 /proc/self/mountinfo 文件中提及。
mount
的手冊說:
保留列表模式只是為了向后兼容。 要獲得更強大和可定制的輸出,請使用 findmnt(8),尤其是在您的腳本中。
所以正確使用的命令是findmnt
,它本身是util-linux
包的一部分,根據手冊:
能夠在 /etc/fstab、/etc/mtab 或 /proc/self/mountinfo 中搜索
所以它實際上比mountpoint
搜索更多的東西。 它還提供了方便的選項:
-M, --mountpoint路徑
顯式定義掛載點文件或目錄。 另見--target。
總之,要檢查目錄是否使用 bash 掛載,您可以使用:
if [[ $(findmnt -M "$FOLDER") ]]; then
echo "Mounted"
else
echo "Not mounted"
fi
例子:
mkdir -p /tmp/foo/{a,b}
cd /tmp/foo
sudo mount -o bind a b
touch a/file
ls b/ # should show file
rm -f b/file
ls a/ # should show nothing
[[ $(findmnt -M b) ]] && echo "Mounted"
sudo umount b
[[ $(findmnt -M b) ]] || echo "Unmounted"
我的解決方案:
is_mount() {
path=$(readlink -f $1)
grep -q "$path" /proc/mounts
}
例子:
is_mount /path/to/var/run/mydir/ || mount --bind /var/run/mydir/ /path/to/var/run/mydir/
對於Mark J. Bobak 的回答,如果在不同的文件系統中使用bind
選項掛載,則掛載mountpoint
不起作用。
對於Christopher Neylan 的回答,不需要將 grep 的輸出重定向到 /dev/null,只需使用grep -q
。
最重要的是,使用readlink -f $mypath
規范化路徑:
/path/to/dir/
以反斜杠結尾,則/proc/mounts
或mount
輸出中的/path/to/dir
為/path/to/dir
/var/run/
是的符號鏈接/run/
,因此,如果您安裝綁定了/var/run/mypath
並檢查是否安裝,它會顯示為/run/mypath
在/proc/mounts
。我喜歡使用/proc/mounts
的答案,但我不喜歡做簡單的 grep。 這可能會給您帶來誤報。 您真正想知道的是“是否有任何行具有字段編號 2 的確切字符串”。 所以,問這個問題。 (在這種情況下,我正在檢查/opt
)
awk -v status=1 '$2 == "/opt" {status=0} END {exit status}' /proc/mounts
# and you can use it in and if like so:
if awk -v status=1 '$2 == "/opt" {status=0} END {exit status}' /proc/mounts; then
echo "yes"
else
echo "no"
fi
這里的答案太復雜了,只需使用以下方法檢查安裝是否存在:
cat /proc/mounts | tail -n 1
這僅輸出最后安裝的文件夾,如果您想查看所有文件夾,只需刪除 tail 命令。
另一個干凈的解決方案是這樣的:
$ mount | grep /dev/sdb1 > /dev/null && echo mounted || echo unmounted
當然,'echo something' 可以用你需要為每種情況做的任何事情來代替。
在我的 .bashrc 中,我做了以下別名:
alias disk-list="sudo fdisk -l"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.