User Tools

Site Tools


tutorials:bash_scripting:part2

This is an old revision of the document!


3. Adding a GUI interface to a bash script

GUI interfaces can be used with bash scripts. The script below uses Zenity to provide a GUI interface for selecting an image to convert to .pdf and a second GUI interface for naming and saving the newly created .pdf file.

#!/bin/bash
############################################################
# con2pdf-gui
# Intended to convert scanned document to pdf document 
# and provides gui interface for file selection.
# requires awk
# requires convert (from ImageMagick)
# requires dirname
# requires zenity to create gui file selection dialogs
# zenity requires GTK+
############################################################
 
input_file=$(zenity --file-selection --title "Select an image file to convert to pdf" --directory ~)
 
	if [ $? -eq 1 ]; then
        exit
    	elif [ $? -eq 1 ]; then
		zenity --error --text "You did not select a file to convert"
		exit
	fi
 
working_dir=$(dirname $input_file)
 
cd $working_dir
 
output_file=$(zenity --file-selection --save --title "Where do you want to save the pdf file?"\
--directory $working_dir --confirm-overwrite)
 
convert $input_file $output_file
 
# end of script

This script could be run by clicking an icon on a desktop and since the interface is GUI there would be no need to open a terminal.

input_file=`zenity --file-selection --title "Select an image file to convert to pdf"`

The first line of this script uses a zenity command within two backticks to assign a file to the variable input_file. The option file-selection specifies that a file selection dialog box is required. The option –title will create a title for the dialog using the text enclosed in double quotes. The option –directory nominates the default directory to be opened. In this instance, ~, will open up the home directory of the current user.

The CLI utility con2pdf either converted an image to a pdf if an image file was entered after the command or it printed out the usage message and retruned to a comman prompt. However, if the user hits the Cancel button or does not select a file, this script will continue to run.

Zenity returns the following exit codes:

  • 0 The user has pressed either OK or Close.
  • 1 The user has pressed Cancel.
  • -1 An unexpected error has occurred, e.g. no file has been selected.
  • 5 The dialog has been closed because the timeout has been reached.

An if/else if (elif) statement can be used to exit the script with a 0 exit code or will open a zenity error dialog and then exit the script if the user presses Cancel or does not select a file to convert.

tutorials/bash_scripting/part2.1330222004.txt.gz · Last modified: 2017/10/12 21:58 (external edit)