Shell 文件测试符例子

2021-08-31 09:53 更新

下面是一个例子,它使用的所有文件测试操作:

假设一个变量的文件保存现有文件名"/var/www/yiibai/unix/test.sh",其大小为100字节,读,写和执行权限:

#!/bin/sh

file="/var/www/yiibai/unix/test.sh"

if [ -r $file ]
then
   echo "File has read access"
else
   echo "File does not have read access"
fi

if [ -w $file ]
then
   echo "File has write permission"
else
   echo "File does not have write permission"
fi

if [ -x $file ]
then
   echo "File has execute permission"
else
   echo "File does not have execute permission"
fi

if [ -f $file ]
then
   echo "File is an ordinary file"
else
   echo "This is sepcial file"
fi

if [ -d $file ]
then
   echo "File is a directory"
else
   echo "This is not a directory"
fi

if [ -s $file ]
then
   echo "File size is zero"
else
   echo "File size is not zero"
fi

if [ -e $file ]
then
   echo "File exists"
else
   echo "File does not exist"
fi

这将产生以下输出结果:

File has read access
File has write permission
File has execute permission
File is an ordinary file
This is not a directory
File size is zero
File exists

记下以下几点:

  • 运算符和表达式之间必须有空格,例如2+2是不正确的,它应该写成2 + 2。
  • if...then...else...fi 语句在下一章节中已经解释的决策声明。

 


    


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号