如何避免在BASH中打印错误?我想做这样的事情。如果用户输入了错误的参数(例如“。”),它将退出程序,而不是在终端上显示错误。 (我没有在这里发布整个代码......这有点长)。 enter image description here
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
答案 0 :(得分:2)
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
# ...