• 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
    }

  • 相关阅读:
    大话领域驱动
    c#之循环效率
    编程思想之——"人是活的,程序是死的"
    C#之系统异常处理机制
    EF操作扩展之async
    C#提供APP接口之JSON差异
    EF操作MySql
    WCF 消息压缩性能问题及解决方法
    [NoSQL]-Elasticsearch 7.9
    [Linux]-Debian10基础使用
  • 原文地址:https://www.cnblogs.com/hxphp/p/6868261.html
Copyright © 2020-2023  润新知