位置:首頁 > 其他技術 > Shell > Shell 文件測試符例子

Shell 文件測試符例子

下麵是一個例子,它使用的所有文件測試操作:

假設一個變量的文件保存現有文件名"/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 語句在下一章節中已經解釋的決策聲明。