Adding an Auto Shutdown Feature to the End of a Script

Whole Script

# Main Script Function ...

# Shutdown Option
export DISPLAY=:0.0;
if [ `/usr/bin/xprintidle` -gt 60000 ]; then
    /usr/bin/zenity --question --title="Job Completed" --timeout=60 \
                    --text="Job Completed; Proceed to Shutdown?" \
                    --ok-label="Yes" --cancel-label="No";
    if [ "$?" -eq "5" ]; then
        # Proceed to Shutdown
        /sbin/shutdown -h now;
    fi
fi

Explanations

export DISPLAY=:0.0;

This is necessary if the script is run outside of an X session (e.g. as a cron job), so that xprintidle can get the correct X session idle time, and zenity can show the dialog on the correct X server display.

if [ `/usr/bin/xprintidle` -gt 60000 ]; then

Gets the X session idle time, and presents the shutdown option if the X session has been inactive for some time (in this case, 60000 milliseconds). Otherwise, it is assumed that the user is active and does not want the system to shutdown.

/usr/bin/zenity --question --title="Job Completed" --timeout=60 \
                --text="Job Completed; Proceed to Shutdown?" \
                --ok-label="Yes" --cancel-label="No";

Displays the shutdown option dialog with the specified title, text, and options. If none of the options is selected within the timeout period (in this case, 60 seconds), the dialog closes with the “Yes” option selected by default.

if [ "$?" -eq "5" ]; then

Shuts down the system if the “Yes” option was selected, or if no option was selected within the timeout period (hence defaulting to the “Yes” option). Otherwise (i.e. the “No” option was selected within the timeout period), the system does not shut down.

/sbin/shutdown -h now;

Shuts down the system.

Note: xprintidle and zenity may not be present in a default installation. They can be installed through the package manager.

References

[1] https://www.linuxquestions.org/questions/linux-newbie-8/export-display%3D-0-0-a-682926/
[2] http://freecode.com/projects/xprintidle
[3] https://help.gnome.org/users/zenity/stable/

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s