如何检查文件系统是否使用脚本挂载

man*_*k13 27 bash mount shell-script

我是脚本新手……我可以做非常基本的事情,但现在我需要帮助。

我有一个本地文件系统,只有在需要备份时才会挂载。

我从这个开始。

#!/bin/bash
export MOUNT=/myfilesystem

if grep -qs $MOUNT /proc/mounts; then
  echo "It's mounted."
else
  echo "It's not mounted."; then
  mount $MOUNT;
fi
Run Code Online (Sandbox Code Playgroud)

正如我所说,我在脚本方面非常基础。我听说你可以mount通过查看返回码来检查命令的状态。

RETURN CODES
       mount has the following return codes (the bits can be ORed):
       0      success
       1      incorrect invocation or permissions
       2      system error (out of memory, cannot fork, no more loop devices)
       4      internal mount bug
       8      user interrupt
       16     problems writing or locking /etc/mtab
       32     mount failure
       64     some mount succeeded
Run Code Online (Sandbox Code Playgroud)

我不知道如何检查。任何指导?

小智 45

许多 Linux 发行版都有该mountpoint命令。它可以显式地用于检查目录是否为挂载点。就这么简单:

#!/bin/bash    
if mountpoint -q "$1"; then
    echo "$1 is a mountpoint"
else
    echo "$1 is not a mountpoint"
fi
Run Code Online (Sandbox Code Playgroud)


Geo*_*e M 23

您可以mount使用 shell 特殊参数来检查和大多数编写良好的可执行文件的状态代码?

来自man bash

? Expands to the exit status of the most recently executed foreground pipeline.

运行mount命令后,立即执行echo $?将打印上一个命令的状态代码。

# mount /dev/dvd1 /mnt
  mount: no medium found on /dev/sr0
# echo $?
  32
Run Code Online (Sandbox Code Playgroud)

并非所有可执行文件都有明确定义的状态代码。至少,它应该以成功 (0) 或失败 (1) 代码退出,但情况并非总是如此。

为了扩展(并更正)您的示例脚本,if为了清晰起见,我添加了一个嵌套结构。这不是测试状态代码和执行操作的唯一方法,但它是学习时最容易阅读的方法。

#!/bin/bash
mount="/myfilesystem"

if grep -qs "$mount" /proc/mounts; then
  echo "It's mounted."
else
  echo "It's not mounted."
  mount "$mount"
  if [ $? -eq 0 ]; then
   echo "Mount success!"
  else
   echo "Something went wrong with the mount..."
  fi
fi
Run Code Online (Sandbox Code Playgroud)

有关“退出和退出状态”的更多信息,您可以参考Advanced Bash-Scripting Guide

  • @ChrisDown “如果你不正确引用的话,分词会吃掉你的孩子。” 生活的话语。 (2认同)

小智 5

还有一种方法:

if findmnt ${mount_point}) >/dev/null 2>&1 ; then
  #Do something for positive result (exit 0)
else
  #Do something for negative result (exit 1)
fi
Run Code Online (Sandbox Code Playgroud)