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
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    `sleep ... >/dev/null 2>&1 || exit 1`? – PesaThe Jan 13 '18 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... –  Jan 13 '18 at 21:40
  • Did you use exactly what I wrote? `sleep "$sleep_time" >/dev/null 2>&1 || exit 1`? – PesaThe Jan 13 '18 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 ...` – William Pursell Jan 13 '18 at 21:50
  • Tangentially, see also [Why is testing “$?” to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – tripleee Jan 31 '23 at 05:48

1 Answers1

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
# ...
PesaThe
  • 7,259
  • 1
  • 19
  • 43