bash-文件表达式

一点例子:

#!/bin/bash

# test-file: Evaluate the status of a file FILE=~/.bashrc

if [ -e "$FILE" ]; then

    if [ -f "$FILE" ]; then

      echo "$FILE is a regular file."

    fi

    if [ -d "$FILE" ]; then

      echo "$FILE is a directory."

    fi

    if [ -r "$FILE" ]; then

      echo "$FILE is readable."

    fi

    if [ -w "$FILE" ]; then

      echo "$FILE is writable."

    fi

    if [ -x "$FILE" ]; then

      echo "$FILE is executable/searchable."

    fi

else

  echo "$FILE does not exist" exit 1

fi

exit

 

   这个脚本会计算赋值给常量 FILE 的文件,并显示计算结果。对于此脚本有两点需要注意。
第一个,在表达式中参数 $FILE 是怎样被引用的。引号并不是必需的,但这是为了防范空参
数。如果 $FILE 的参数展开是一个空值,就会导致一个错误(操作符将会被解释为非空的字
符串而不是操作符)。用引号把参数引起来就确保了操作符之后总是跟随着一个字符串,即使
字符串为空。第二个,注意脚本末尾的 exit 命令。这个 exit 命令接受一个单独的,可选的参
数,其成为脚本的退出状态。当不传递参数时,退出状态默认为零。以这种方式使用 exit 命
令,则允许此脚本提示失败如果 $FILE 展开成一个不存在的文件名。这个 exit 命令出现在脚
本中的最后一行,是一个当一个脚本“运行到最后”(到达文件末尾),不管怎样,默认情况下
它以退出状态零终止。
类似地,通过带有一个整数参数的 return 命令,shell 函数可以返回一个退出状态。如果我
们打算把上面的脚本转变为一个 shell 函数,为了在更大的程序中包含此函数,我们用 return
语句来代替 exit 命令,则得到期望的行为:

test_file () {
  FILE=~/.bashrc
  if [ -e "$FILE" ]; then
    if [ -f "$FILE" ]; then
      echo "$FILE is a regular file."
    fi
    if [ -d "$FILE" ]; then
      echo "$FILE is a directory."
    fi
    if [ -r "$FILE" ]; then
      echo "$FILE is readable."
    fi
    if [ -w "$FILE" ]; then
      echo "$FILE is writable."
    fi
    if [ -x "$FILE" ]; then
      echo "$FILE is executable/searchable."
    fi
  else
    echo "$FILE does not exist"
    return 1
  fi
}

posted @ 2017-05-17 16:38  不弃初衷  阅读(171)  评论(0编辑  收藏  举报