📌  相关文章
📜  用于检查目录是否存在的 shell 脚本 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:40:54.663000             🧑  作者: Mango

用于检查目录是否存在的 shell 脚本

如果你需要在 shell 脚本中检查一个目录是否存在,可以使用以下脚本:

#!/bin/bash
if [ -d "/path/to/directory" ]
then
  echo "Directory exists."
else
  echo "Directory does not exist."
fi

在上面的脚本中, /path/to/directory 是要检查的目录路径。

-d 参数用于检查一个文件是否为目录,如果是目录,则返回真值。如果目录存在,echo "Directory exists." 将会输出 "Directory exists.", 否则将会输出 "Directory does not exist."。

你也可以将目录路径作为脚本的一个参数,并根据参数来检查相应的目录是否存在。例如:

#!/bin/bash
if [ -d "$1" ]
then
  echo "Directory $1 exists."
else
  echo "Directory $1 does not exist."
fi

在这个脚本中, $1 是第一个脚本参数,即要检查的目录路径。如果目录存在,将会输出 "Directory /path/to/directory exists."(假设你运行的命令是 ./my_script.sh /path/to/directory),否则将会输出 "Directory /path/to/directory does not exist."

如何运行这些脚本?在终端中输入以下命令:

chmod +x my_script.sh
./my_script.sh /path/to/directory

第一行命令 chmod +x my_script.sh 用于将 my_script.sh 脚本设置为可执行,这样你就可以直接运行它。第二行命令 ./my_script.sh /path/to/directory 将运行脚本并将 /path/to/directory 作为参数传递到脚本中。

上面的脚本可以帮助你快速检查一个目录是否存在。如果你想做更多的事情,例如创建一个目录,你可以使用以下脚本:

#!/bin/bash
if [ ! -d "$1" ]
then
  echo "Directory $1 does not exist. Creating directory..."
  mkdir -p $1
  echo "Directory created."
else
  echo "Directory $1 already exists."
fi

在这个脚本中,如果目录不存在,将会创建这个目录。可以使用 mkdir -p 命令来创建多层目录。

祝你编写愉快的 Shell 脚本!