【问题标题】:Redirect output to /dev/null only if VERBOSE is not set仅当未设置 VERBOSE 时才将输出重定向到 /dev/null
【发布时间】:2021-03-17 19:46:10
【问题描述】:

你会如何做到这一点?

if [[ -z $VERBOSE ]]; then
    REDIRECT=">/dev/null 2>/dev/null"
fi

echo "Installing Pip packages"  # Edited in for clarity
pip install requirements.txt $REDIRECT

echo "Installing other dependency"
<Install command goes here> $REDIRECT

【问题讨论】:

    标签: bash shell environment-variables output-redirect


    【解决方案1】:

    您可以使用exec 重定向所有输出:

    if [[ -z $VERBOSE ]]; then
        exec >/dev/null 2>&1
    fi
    
    pip install requirements.txt
    

    如果您想稍后在脚本中恢复输出,您可以复制文件描述符:

    if [[ -z $VERBOSE ]]; then
        exec 3>&1
        exec 4>&2
        exec >/dev/null 2>&1
    fi
    
    # all the commands to redirect output for
    pip install requirements.txt
    # ...
    
    # restore output
    if [[ -z $VERBOSE ]]; then
        exec 1>&3
        exec 2>&4
    fi
    

    另一种选择是打开文件描述符到/dev/null 或复制描述符1

    if [[ -z $VERBOSE ]]; then
        exec 3>/dev/null
    else
        exec 3>&1
    fi
    
    echo "Installing Pip packages"
    pip install requirements.txt >&3
    
    

    【讨论】:

      【解决方案2】:

      exec 没有命令:

      #!/usr/bin/env bash
      
      if [[ ${VERBOSE:-0} -eq 0  ]]; then
         exec >/dev/null 2>/dev/null
      fi
      
      echo "Some text."
      

      例子:

      $ ./example.sh
      $ VERBOSE=1 ./example.sh
      Some text.
      

      如果变量name 未设置或设置为空字符串,则${name:-word} 扩展为word。这样您也可以让VERBOSE=0 将其关闭。

      【讨论】:

      • 有没有办法根据我对我的问题的编辑要求根据脚本要求按需打开和关闭它?因为这行得通,但这不是我想做的。
      猜你喜欢
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2019-10-11
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多