Linux Bash 脚本:操作文件和目录的示例
Linux Bash 脚本:操作文件和目录的示例
本教程将展示一个简单的 Linux Bash 脚本,用于检查文件或目录是否存在,并根据不同的情况进行创建、删除或修改操作。我们将使用 vim 和 cat 编辑和查看脚本,并提供不同运行结果的截图。
程序脚本内容
#!/bin/bash
# 检查/root/test/logical是否存在
if [ ! -e '/root/test/logical' ]; then
# 不存在,创建文件
touch '/root/test/logical'
elif [ -f '/root/test/logical' ]; then
# 存在且为文件,删除文件并创建目录
rm '/root/test/logical'
mkdir '/root/test/logical'
elif [ -d '/root/test/logical' ]; then
# 存在且为目录,移除目录
rm -r '/root/test/logical'
fi
使用 vim 截图

使用 cat 截图

运行结果截图
- /root/test/logical 不存在的情况:

- /root/test/logical 存在且为文件的情况:

- /root/test/logical 存在且为目录的情况:

原文地址: https://www.cveoy.top/t/topic/n0np 著作权归作者所有。请勿转载和采集!