1

How to avoid printing an error in Bash? I want to do something like this. If the user enters a wrong argument (like a "." for example), it will just exit the program rather than displaying the error on the terminal. (I've not posted the whole code here... That's a bit long).

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
5
  • 1
    sleep ... >/dev/null 2>&1 || exit 1? Commented Jan 13, 2018 at 21:37
  • sleep: invalid time interval ‘.’ Try 'sleep --help' for more information. I'm getting this error... I want not to display the error... Commented Jan 13, 2018 at 21:40
  • Did you use exactly what I wrote? sleep "$sleep_time" >/dev/null 2>&1 || exit 1? Commented Jan 13, 2018 at 21:42
  • 1
    There's no need for the rather ugly if [ "$?" -eq 0 ]. It is much cleaner to write if sleep $sleep_time 2> /dev/null; then ... Commented Jan 13, 2018 at 21:50
  • Tangentially, see also Why is testing “$?” to see if a command succeeded or not, an anti-pattern? Commented Jan 31, 2023 at 5:48

1 Answer 1

2

2>/dev/null will discard any errors. Your code can be simplified like this:

#!/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
# ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.