1

I am trying to write a script. In the beginning of the script, I want it to check for internet connectivity and then continue, else the script should stops with message "please check your internet". I am new in bash programming, that why I am not sure that whether "if-then-else" should be used here or "while". Here is my script:

#!/bin/bash if ping -c 1 google.com >& /dev/null then echo "INTERNET IS WORKING..." else echo "PLEASE CHECK YOUR INTERNET!" fi cd $HOME/download pwd 

In this script, in case the "if" statement fails, and the script runs the "else" statement, I want this script to stop, instead of going further to "cd $HOME/download" and "pwd".

How can I do this in this script?

    1 Answer 1

    2
    #!/bin/bash if ping -c 1 google.com >& /dev/null then echo "INTERNET IS WORKING..." else echo "PLEASE CHECK YOUR INTERNET!" >&2 exit 1 fi cd "$HOME/download" || exit 2 pwd 

    I also changed

    echo "PLEASE CHECK YOUR INTERNET!" 

    to print error message to standard error and

    cd $HOME/download 

    to

    cd "$HOME/download" || exit 2 

    to exit if cd failed, for example because "$HOME/download" does not exist. There are no more warnings reported by shellcheck.

    8
    • 1
      Or just if ! ping ...; then exit 1; fi
      – Kusalananda
      CommentedApr 28, 2020 at 20:34
    • Arkadiusz Drabczyk: It worked perfectly... Thanks a lot man :-) Kusalananda: Interesting, I will definitely check it.CommentedApr 28, 2020 at 20:36
    • @Kusalananda: from what I understood, OP always wants to print something on the screen so it would be if ! ping ...; then echo INTERNET IS NOT WORKING >&2; exit 1; fi but at least else wouldn't be neededCommentedApr 28, 2020 at 20:41
    • Yes, I always want "Some Message" to be printed on screen. I have a further query in this regard: If I want to use 'exit' again then should I go with exit 3, exit 4 and so on?CommentedApr 28, 2020 at 20:44
    • @SalmanAhmed: it's up to you, everything non-zero means failure. If there are a lot of places in which your script could exit with failure incrementing exit status might get daunting very quickly. In that case exit 1 plus a clear error message would be enough. If there are only a few places in which your script could exit, I'd increment exit status with each non-success exit so that caller immediately knows what's happened just by looking at $?.CommentedApr 28, 2020 at 20:51

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.