编写一个shell脚本checkfile.sh,判断一个文件是否具有可写可执行的权限。命令格式:./checkfile.sh 文件名 如果文件可写可读,对应地在终端输出“read and write”字样;如果只能写,那么输出"write",如果只能读,那么输出"read"。(自行创建三个测试文件,其中a.txt可读可写,b.txt只能写,c.txt只能读)
时间: 2024-02-17 14:00:36 浏览: 82
shell判断文件,目录是否存在或者具有权限的代码
请见下面的shell脚本checkfile.sh,它可以根据输入的文件名判断文件是否具有可写可执行的权限:
```bash
#!/bin/bash
if [ -r "$1" ] && [ -w "$1" ] && [ -x "$1" ]; then
echo "read and write and execute"
elif [ -w "$1" ] && [ -x "$1" ]; then
echo "write and execute"
elif [ -r "$1" ] && [ -x "$1" ]; then
echo "read and execute"
elif [ -x "$1" ]; then
echo "execute only"
elif [ -w "$1" ]; then
echo "write only"
elif [ -r "$1" ]; then
echo "read only"
else
echo "no read or write or execute permission"
fi
```
该脚本首先判断文件是否具有可读、可写、可执行的权限,如果是则输出“read and write and execute”;如果只有可写和可执行权限,则输出“write and execute”;如果只有可读和可执行权限,则输出“read and execute”;如果只有可执行权限,则输出“execute only”;如果只有可写权限,则输出“write only”;如果只有可读权限,则输出“read only”;如果没有任何权限,则输出“no read or write or execute permission”。
以下是对三个测试文件的测试结果:
对于可读可写可执行的文件a.txt,输出“read and write and execute”:
```bash
$ ./checkfile.sh a.txt
read and write and execute
```
对于只有可写权限的文件b.txt,输出“write only”:
```bash
$ ./checkfile.sh b.txt
write only
```
对于只有可读权限的文件c.txt,输出“read only”:
```bash
$ ./checkfile.sh c.txt
read only
```
阅读全文