zoukankan      html  css  js  c++  java
  • 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
    }

  • 相关阅读:
    直击 KubeCon 2019 现场,阿里云 Hands-on Workshop 亮点回顾
    分享 KubeCon 2019 (上海)关于 Serverless 及 Knative 相关演讲会议
    MaxCompute 费用暴涨之新增SQL分区裁剪失败
    UI2CODE复杂背景无法识别?闲鱼工程师这样打造高准确率方案
    阿里云发布边缘容器,云边端一体化时代来临
    中间件性能挑战赛上线了两大黑科技,是高手就盘它!!
    MaxCompute 费用暴涨之存储压缩率降低导致SQL输入量变大
    通知: Spring Cloud Alibaba 仓库迁移
    MaxCompute 项目子账号做权限管理
    性能压测工具选型对比
  • 原文地址:https://www.cnblogs.com/hxphp/p/6868261.html
Copyright © 2011-2022 走看看