Shell编程-文件运算符

时间:2020-02-23 14:45:07  来源:igfitidea点击:

在本教程中,我们将学习Shell编程中的文件运算符。

我们将使用if语句执行测试。

我们将使用变量file来存储文件名,并设置了读取,写入和执行权限。

注意!要更改文件许可权,请使用以下命令。

$chmod 755 filename

或者,如果您想授予所有人访问权限,请使用" chmod 777 filename"。

例:

在以下示例中,我们将设置helloworld.txt文件的权限。

$chmod 755 helloworld.txt

文件运算符

运算符注意
-e检查文件是否存在。
-r检查文件是否可读。
-w检查文件是否可写。
-x检查文件是否可执行。
-s检查文件大小是否大于0。
-d检查文件是否为目录。

例1:编写一个Shell脚本来检查文件是否存在

在下面的示例中,我们将检查helloworld.txt是否存在。

#!/bin/sh

file="/Users/theitroad/Documents/GitHub/shell-script/example/file/helloworld.txt"

# check
if [ -e $file ]
then
  echo "File exists!"
else
  echo "File does not exists!"
fi
$sh example01.sh 
File exists!

例2:编写Shell脚本以检查目录

#!/bin/sh

file="/Users/theitroad/Documents/GitHub/shell-script/example/file"

# check
if [ -d $file ]
then
  echo "Directory exists!"
else
  echo "Directory does not exists!"
fi
$sh example02.sh 
Directory exists!

例3:编写Shell脚本以检查文件是否可读,可写和可执行

#!/bin/sh

file="/Users/theitroad/Documents/GitHub/shell-script/example/file/helloworld.txt"

# check
if [ -e $file ]
then
  echo "File exists!"

  # check readable
  if [ -r $file ]
  then
    echo "File is readable."
  else
  	echo "File is not readable."
  fi

  # check writable
  if [ -w $file ]
  then
    echo "File is writable."
  else
  	echo "File is not writable."
  fi

  # check executable
  if [ -x $file ]
  then
    echo "File is executable."
  else
  	echo "File is not executable."
  fi

else
  echo "File does not exists!"
fi
$sh example03.sh 
File exists!
File is readable.
File is writable.
File is executable.