shell 脚本 检查文件是否存在
时间: 2023-10-23 09:10:59 浏览: 44
在shell脚本中,可以使用`-f`参数来检查文件是否存在。例如,下面的代码段会检查文件`/path/to/file`是否存在:
```
if [ -f /path/to/file ]; then
echo "文件存在"
else
echo "文件不存在"
fi
```
如果文件存在,则会输出`文件存在`,否则会输出`文件不存在`。
相关问题
shell脚本检查文件是否存在
可以使用 `test` 命令或者 `[ ]` 来检查文件是否存在,例如:
```bash
#!/bin/bash
if [ -e "/path/to/file" ]
then
echo "file exists"
else
echo "file does not exist"
fi
```
其中 `-e` 参数表示文件是否存在,如果存在则返回 true,否则返回 false。如果使用 `test` 命令,可以将 `-e` 参数放在文件名之前,例如:`test -e /path/to/file`。
shell脚本查看文件是否存在
要在 shell 脚本中查看文件是否存在,你可以使用 `test` 命令来测试文件是否存在。例如,下面的脚本用来检查名为 `/etc/passwd` 的文件是否存在:
```
#!/bin/bash
if test -e /etc/passwd; then
echo "文件存在"
else
echo "文件不存在"
fi
```
你也可以使用 `[ -e /etc/passwd ]` 来测试文件是否存在。
此外,你还可以使用 `ls` 命令来检查文件是否存在。例如,`ls /etc/passwd` 命令会检查 `/etc/passwd` 文件是否存在,如果存在,则输出文件名,如果不存在,则输出错误信息。
```
#!/bin/bash
if ls /etc/passwd > /dev/null 2>&1; then
echo "文件存在"
else
echo "文件不存在"
fi
```