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
    }

  • 相关阅读:
    DZY Loves Sequences
    Boredom easy dp
    floyd算法 poj1125
    poj3259 Bellman_Ford算法
    poj1860 Bellman_Ford算法
    Java 获取资源文件路径
    CLion 2020.1.2 激活
    Kotlin学习笔记
    Kotlin Hello World
    WebStorm 2020.1.2 激活
  • 原文地址:https://www.cnblogs.com/hxphp/p/6868261.html
Copyright © 2011-2022 走看看