【问题标题】:Elegant way for verbose mode in scripts?脚本中详细模式的优雅方式?
【发布时间】:2012-01-17 08:46:02
【问题描述】:

当我编写 bash 脚本时,我通常会以这种方式获得详细模式(简化):

_V=0

while getopts "v" OPTION
do
  case $OPTION in
    v) _V=1
       ;;
  esac
done

然后每次我想要“详细输出”时,我都会输入:

[ $_V -eq 1 ] && echo "verbose mode on" || echo "verbose mode off"

或者例如这个:

[ $_V -eq 1 ] && command -v || command

有没有办法让它更优雅?我正在考虑定义一个名为“verbose”的函数并输入它而不是[ $_V -eq 1 ],但这只是一个微小的改进。

我敢肯定,有更常见的方法来做到这一点……

【问题讨论】:

标签: bash logging verbosity


【解决方案1】:

如您所见,您可以定义一些 log 函数,例如 log、log_debug、log_error 等。

function log () {
    if [[ $_V -eq 1 ]]; then
        echo "$@"
    fi
}

它可以帮助增加您的主要代码的可读性并将显示\非显示逻辑隐藏到日志功能中。

log "some text"

如果_V(全局变量) 等于1 将打印“一些文本”,否则不会打印。

【讨论】:

    【解决方案2】:

    在阅读了所有其他帖子后,我想出了这个

    # set verbose level to info
    __VERBOSE=6
    
    declare -A LOG_LEVELS
    # https://en.wikipedia.org/wiki/Syslog#Severity_level
    LOG_LEVELS=([0]="emerg" [1]="alert" [2]="crit" [3]="err" [4]="warning" [5]="notice" [6]="info" [7]="debug")
    function .log () {
      local LEVEL=${1}
      shift
      if [ ${__VERBOSE} -ge ${LEVEL} ]; then
        echo "[${LOG_LEVELS[$LEVEL]}]" "$@"
      fi
    }
    

    那你就可以这么简单地使用了

    # verbose error
    .log 3 "Something is wrong here"
    

    哪个会输出

    [error] Something is wrong here
    

    【讨论】:

    • 这比其他答案的开/关方式要好得多。作为向量的字符串和值之间的映射是一个很好的附加组件,它类似于 Python 中的实现。
    【解决方案3】:
    #!/bin/bash
    # A flexible verbosity redirection function
    # John C. Petrucci (http://johncpetrucci.com)
    # 2013-10-19
    # Allows your script to accept varying levels of verbosity flags and give appropriate feedback via file descriptors.
    # Example usage: ./this [-v[v[v]]]
    
    verbosity=2 #Start counting at 2 so that any increase to this will result in a minimum of file descriptor 3.  You should leave this alone.
    maxverbosity=5 #The highest verbosity we use / allow to be displayed.  Feel free to adjust.
    
    while getopts ":v" opt; do
        case $opt in
            v) (( verbosity=verbosity+1 ))
            ;;
        esac
    done
    printf "%s %d\n" "Verbosity level set to:" "$verbosity"
    
    for v in $(seq 3 $verbosity) #Start counting from 3 since 1 and 2 are standards (stdout/stderr).
    do
        (( "$v" <= "$maxverbosity" )) && echo This would display $v 
        (( "$v" <= "$maxverbosity" )) && eval exec "$v>&2"  #Don't change anything higher than the maximum verbosity allowed.
    done
    
    for v in $(seq $(( verbosity+1 )) $maxverbosity ) #From the verbosity level one higher than requested, through the maximum;
    do
        (( "$v" > "2" )) && echo This would not display $v 
        (( "$v" > "2" )) && eval exec "$v>/dev/null" #Redirect these to bitbucket, provided that they don't match stdout and stderr.
    done
    
    # Some confirmations:
    printf "%s\n" "This message is seen at verbosity level 3 and above." >&3
    printf "%s\n" "This message is seen at verbosity level 4 and above." >&4
    printf "%s\n" "This message is seen at verbosity level 5 and above." >&5
    

    【讨论】:

      【解决方案4】:

      我也想出了这个函数来做一个快速的ifelse:

      function verbose () {
          [[ $_V -eq 1 ]] && return 0 || return 1
      }
      

      如果 $_V 设置为 1,这将执行一个命令。像这样使用它:

      verbose && command #command will be executed if $_V == 1
      

      或

      verbose && command -v || command # execute 'command -v' if $_V==1, else execute 'command'
      

      【讨论】:

        【解决方案5】:

        如果您想避免每次要记录某些内容时都执行“if”语句,您可以尝试这种方法(我就是这样做的)。

        这个想法是,而不是调用log,而是调用$echoLog。因此,如果您处于详细模式,$echoLog 将只是 echo,但在非详细模式下,它是一个不打印任何内容并忽略参数的函数。

        这里有一些你可以复制的代码。

        # Use `$echoLog` everywhere you print verbose logging messages to console
        # By default, it is disabled and will be enabled with the `-v` or `--verbose` flags
        declare echoLog='silentEcho'
        function silentEcho() {
            :
        }
        
        # Somewhere else in your script's setup, do something like this
        while [[ $# > 0 ]]; do
            case "$1" in
                -v|--verbose) echoLog='echo'; ;;
            esac
            shift;
        done
        

        现在,您可以将$echoLog "Doing something verbose log worthy" 之类的行放到任何您想要的地方。

        【讨论】:

          【解决方案6】:

          第一次尝试具有详细级别的更灵活的系统(Bash 4):

          # CONFIG SECTION
          # verbosity level definitions
          config[verb_levels]='debug info status warning error critical fatal'
          
          # verbosity levels that are to be user-selectable (0-this value)
          config[verb_override]=3
          
          # user-selected verbosity levels (0=none, 1=warnings, 2=warnings+info, 3=warning+info+debug)
          config[verbosity]=2
          
          # FUNCTION DEFINITIONS SECTION
          _messages() {
              # shortcut functions for messages
              # non overridable levels exit with errlevel
              # safe eval, it only uses two (namespaced) values, and a few builtins
              local verbosity macro level=0
              for verbosity in ${config[verb_levels]}; do
                  IFS="" read -rd'' macro <<MACRO
                  _$verbosity() {
                      $( (( $level <= ${config[verb_override]} )) && echo "(( \${config[verbosity]} + $level > ${config[verb_override]} )) &&" ) echo "${verbosity}: \$@";
                      $( (( $level > ${config[verb_override]} )) && echo "exit $(( level - ${config[verb_override]} ));" )
                  }
          MACRO
                  eval "$macro"
                  (( level++ ))
              done
          }
          
          # INITIALIZATION SECTION
          _messages
          

          初始化后,您可以在代码中的任何位置使用以下内容:

          ! (( $# )) && _error "parameter expected"
          
          [[ -f somefile ]] && _warning "file $somefile already exists"
          
          _info "some info"
          
          _status "running command"
          if (( ${config[verbosity]} <= 1 )); then
              command
          else
              command -v
          fi
          
          # explicitly changing verbosity at run time
          old_verbosity=${config[verbosity]}
          config[verbosity]=1
          

          等等

          【讨论】:

          • 哇!这无论如何都适用于 Bash 3 吗? (我仅限于 Bash 3.2)
          【解决方案7】:
          verbose=false
          
          while getopts "v" OPTION
          do
            case $OPTION in
              v) verbose=true
                 ;;
            esac
          done
          

          然后

          $verbose && echo "Verbose mode on" || echo "Verbose mode off"
          

          这将执行/bin/true 或/bin/false,分别返回0 或1。

          【讨论】:

          • true 或 false 不会被执行,你只是在处理字符串。
          【解决方案8】:

          为了避免使用多个 if 语句或使用变量来保存函数名称,如何根据详细程度声明不同的函数!

          这适用于所有 bourne shell 衍生品,而不仅仅是 bash!

          #verbose=verbose_true       # uncomment to make script verbose
          if [ "$verbose" ]; then
            log() { echo "$@"; }
          else
            log() { :; }
          fi
          
          log This Script is Verbose
          

          注意:“verbose=verbose_true”的使用使脚本跟踪更好 但如果你愿意,你可以做那个。

          【讨论】:

            【解决方案9】:

            我会建议@fentas的答案的修改版本:

            # set verbose level to info
            __VERBOSE=6
            
            declare -A LOG_LEVELS
            # https://en.wikipedia.org/wiki/Syslog#Severity_level
            LOG_LEVELS=([0]="emerg" [1]="alert" [2]="crit" [3]="err" [4]="warning" [5]="notice" [6]="info" [7]="debug")
            function .log () {
              local LEVEL=${1}
              shift
              if [ ${__VERBOSE} -ge ${LEVEL} ]; then
                if [ -t 0 ]; then
                  # seems we are in an interactive shell
                  echo "[${LOG_LEVELS[$LEVEL]}]" "$@" >&2
                else
                  # seems we are in a cron job
                  logger -p "${LOG_LEVELS[$LEVEL]}" -t "$0[$$]" -- "$*"
                fi
              fi
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2021-05-25
              • 2011-08-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多