Shell Mount并检查directionairy存在

时间:2017-03-14 10:31:03

标签: linux bash shell mount

只是寻找安装shell脚本的一些帮助,想知道是否有人可以建议我如何检查挂载点上的目录是否存在且为空,或者如果脚本不存在则由脚本创建< / p>

#!/bin/bash

MOUNTPOINT="/myfilesystem"

if grep -qs "$MOUNTPOINT" /proc/mounts; then
    echo "It's mounted."
else
    echo "It's not mounted."

    mount "$MOUNTPOINT"

    if [ $? -eq 0 ]; then
        echo "Mount success!"
    else
        echo "Something went wrong with the mount..."
    fi
fi

2 个答案:

答案 0 :(得分:2)

您对/myfilesystem的使用将返回包含字符串/myfilesystem的任何挂载点...例如:以下两者:

  • /home/james/myfilesystem
  • mountpoint -q "${MOUNTPOINT}"

喜欢使用更具说明性的内容,如下所示:

[

您可以使用if [ ! -d "${MOUNTPOINT}" ]; then if [ -e "${MOUNTPOINT}" ]; then echo "Mountpoint exists, but isn't a directory..." else echo "Mountpoint doesn't exist..." fi fi 来测试路径是否是目录:

mkdir -p

mkdir -p "${MOUNTPOINT}" 将根据需要创建所有父目录:

[ "$(echo ${MOUNTPOINT}/*)" != "${MOUNTPOINT}/*" ]

最后,通过利用bash的变量扩展来测试目录是否为空:

set

运行具有某种“安全性”级别的脚本也是一个好主意。请参阅-e Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status. -u Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion. 内置命令:https://linux.die.net/man/1/bash

bash -eu

完整:(注意#!/bin/bash -eu MOUNTPOINT="/myfilesystem" if [ ! -d "${MOUNTPOINT}" ]; then if [ -e "${MOUNTPOINT}" ]; then echo "Mountpoint exists, but isn't a directory..." exit 1 fi mkdir -p "${MOUNTPOINT}" fi if [ "$(echo ${MOUNTPOINT}/*)" != "${MOUNTPOINT}/*" ]; then echo "Mountpoint is not empty!" exit 1 fi if mountpoint -q "${MOUNTPOINT}"; then echo "Already mounted..." exit 0 fi mount "${MOUNTPOINT}" RET=$? if [ ${RET} -ne 0 ]; then echo "Mount failed... ${RET}" exit 1 fi echo "Mounted successfully!" exit 0

{{1}}

答案 1 :(得分:1)

以下是如何检查目录是否存在且为空:
if [ -d /myfilesystem ] && [ ! "$(ls -A /myfilesystem/)" ]; then echo "Directory exist and it is empty" else echo "Directory doesnt exist or not empty" fi