gpt4 book ai didi

linux - shell 安装并检查方向是否存在

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:46:53 25 4
gpt4 key购买 nike

只是在我的安装 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

最佳答案

您使用 grep 将返回任何包含字符串 /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}/*" ]

以一定程度的“安全”运行脚本也是一个好主意。查看 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

关于linux - shell 安装并检查方向是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42783516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com