Shell 安装并检查方向是否存在

Shell Mount and check directionairy existence

只是在为我的挂载 shell 脚本寻求一些帮助,想知道是否有人可以建议我如何让它检查挂载点处的目录是否存在且为空,或者是由脚本创建的如果不存在

#!/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

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

您对 grep 的使用将 return 任何包含字符串 /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}"

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

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

运行 具有一定程度 'safety' 的脚本也是一个好主意。请参阅 set 内置命令:https://linux.die.net/man/1/bash

-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.

全文:(注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