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
}

转载于:https://www.cnblogs.com/hxphp/p/6868261.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值