shell 如何避免在执行命令时在控制台的BASH脚本中打印错误?

rur96b6h  于 2023-01-31  发布在  Shell
关注(0)|答案(1)|浏览(187)

如何避免在BASH中打印错误?我想做一些类似的事情。如果用户输入了一个错误的参数(例如“.”),它将退出程序,而不是在终端上显示错误。(我没有在这里发布完整的代码...这有点长)。

if [ -n "$1" ]; then
        sleep_time=$1
        # it doesn't work, and displays the error on the screen
        sleep $sleep_time > /dev/null
        if [ "$?" -eq 0 ]; then
                measurement $sleep_time
        else
                exit
        fi

# if invalid arguments passed, take the refreshing interval from the user
else
        echo "Proper Usage: $0 refresh_interval(in seconds)"
        read -p "Please Provide the  Update Time: " sleep_time
        sleep $sleep_time > /dev/null
        if [ "$?" -eq 0 ]; then
                measurement  $sleep_time
        else
                exit
        fi
fi
x8goxv8g

x8goxv8g1#

2>/dev/null将丢弃所有错误。您的代码可以简化如下:

#!/usr/bin/env bash

if [[ $# -eq 0 ]]; then
    echo "Usage: $0 refresh_interval (in seconds)"
    read -p "Please provide time: " sleep_time
else
    sleep_time=$1
fi

sleep "$sleep_time" 2>/dev/null || { echo "Wrong time" >&2; exit 1; }

# everything OK - do stuff here
# ...

相关问题