user9156891
user9156891

Reputation:

How to avoid printing an error in the console in a Bash script when executing a command?

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

Upvotes: 1

Views: 1106

Answers (1)

PesaThe
PesaThe

Reputation: 7499

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
# ...

Upvotes: 2

Related Questions