Posted: . At: 9:03 AM. This was 5 years ago. Post ID: 13559
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Some very useful bash scripting tips for testing the output of a program.


This simple shell script will test your Internet connection and then tell you if it is up or not.

wgetvar=$(wget -q --tries=3 --timeout=20 --spider http://google.com)
 
if [ $? -eq '0' ]
         then
            echo "Internet is up."
         else
            #some logging
            echo "Internet is down.."
fi

This section will test if the program run at the start of the script returns 0 or not. If it has a return value of 0, then it ran successfully. Then the Internet connection is up.

if [ $? -eq '0' ]

Another way is to do this.

if [ $? -ne '1' ]

This tests if the program did not return 1. This also could return other numbers. It is better to check for the 0 return value if the scripter desires to know if a program was successful in execution.

The Linux Documentation Project has a list of reserved codes that also offers advice on what code to use for specific scenarios. These are the standard error codes in Linux or UNIX.

  • 1 – Catchall for general errors
  • 2 – Misuse of shell builtins (according to Bash documentation)
  • 126 – Command invoked cannot execute
  • 127 – “command not found”
  • 128 – Invalid argument to exit
  • 128+n – Fatal error signal “n”
  • 130 – Script terminated by Control-C
  • 255\* – Exit status out of range

This example is a case statement, this will be a good base for a script to start or stop a service, or to accept other parameters.

case "$1" in
    start)
        echo "Start"
        ;;
    stop)
        echo "Stop"
        ;;
esac

This would be useful for a script that has to do one thing or another depending upon the parameters issued to it.

This is from the /etc/init.d/gdm3 script, this is an example of the else if syntax in bash scripting.

        elif [ -e "$DEFAULT_DISPLAY_MANAGER_FILE" ] && \
           [ "$HEED_DEFAULT_DISPLAY_MANAGER" = "true" ] && \
           [ "$CONFIGURED_DAEMON" != gdm3 ] ; then
                log_action_msg "Not starting GNOME Display Manager; it is not the default display manager"
        else

This can also be used in a script to do something else when running the script.

With the case statement, it is also possible to use multiple options for each parameter.

case "$1" in
    start|force-reload|restart|reload)
        echo "Starting the server"
        ;;
    stop|shutdown)
        echo "Stopping the server deamon"
        ;;
esac

So issuing a command to force-reload, is the same as starting or reloading the service.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.