10 Tools to Increase the Fun of UNIX/Linux Shell Scripts

There are some misconceptions that shell scripts are only used in the CLI environment. In fact, under the KDE or Gnome desktop, you can effectively use a variety of tools to write GUI or socket scripts. Shell scripts can use some GUI components (menus, warning boxes, progress bars, etc.). You can control terminal output, cursor position, various output effects, and more. With the following tools, you can build strong, interactive, user-friendly UNIX/Linux bash scripts.

Making GUI applications is not a difficult task, but it takes time and patience. Fortunately, both UNIX and Linux come with a large number of tools for writing beautiful GUI scripts. The following tools are based on the FreeBSD and Linux operating system tests, but also apply to other UNIX-like operating systems.

1, notify-send command

The notify-send command allows you to use the notification daemon to send desktop notifications to users. This way of avoiding bothering the user is useful for informing the desktop user of an event or displaying some information. On Debian or Ubuntu, you need to install packages using the apt command or the apt-get command:

Sudo apt-get install libnotify-bin

CentOS/RHEL users use the following yum command:

Sudo yum install libnotify

Fedora Linux users use the following dnf command:

`$ sudo dnf install libnotify`

In this example, send simple desktop notification from the command line, enter:

### send some notification ###

Notify-send "rsnapshot done :)"

Sample output:

Notify-send: Shell Script Get Or Send Desktop Notifications

Here is the code for another additional option:

...

Alert=18000

Live=$(lynx --dump http://money.rediff.com/ | grep 'BSE LIVE' | awk '{ print $5}' | sed 's/,//g;s/\.[0-9 ]*//g')

[ $notify_counter -eq 0 ] && [ $live -ge $alert ] && { notify-send -t 5000 -u low -i "BSE Sensex touched 18k"; notify_counter=1; }

...

Sample output:

Linux / UNIX: Display Notifications From Your Shell Scripts With notify-send

Here:

-t 5000: specifies the timeout (in milliseconds) (5000 milliseconds = 5 seconds)

-u low: Set emergency level (eg low, normal, emergency)

-i gtk-dialog-info: Set the name of the icon to be displayed or the specified icon (you can set the path to: -i /path/to/your-icon.png)

For more information on using the notify-send feature, refer to the man manual. Enter man notify-send at the command line to see:

Man notify-send

2, tput command

The tput command is used to set terminal features. With tput you can set:

Move the cursor on the screen.

Get terminal information.

Set the color (background and foreground).

Set bold mode.

Set reverse mode and so on.

Here is a sample of code:

#!/bin/bash

# clear the screen

Tput clear

# Move cursor to screen location X,Y (top left is 0,0)

Tput cup 3 15

# Set a foreground colour using ANSI escape

Tput setaf 3

Echo "XYX Corp LTD."

Tput sgr0

Tput cup 5 17

# Set reverse video mode

Tput rev

Echo "MAIN - MENU"

Tput sgr0

Tput cup 7 15

Echo "1. User Management"

Tput cup 8 15

Echo "2. Service Management"

Tput cup 9 15

Echo "3. Process Management"

Tput cup 10 15

Echo "4. Backup"

# Set bold mode

Tput bold

Tput cup 12 15

Read -p "Enter your choice [1-4] " choice

Tput clear

Tput sgr0

Tput rc

Sample output:

Linux / UNIX Script Colours and Cursor Movement With tput

For details on the tput command, see the manual:

Man 5 terminfo

Man tput

3, setleds command

The setleds command allows you to set the keyboard lights. Here is an example of opening a digital key light:

Setleds -D +num

Turn off the digital key light and enter:

Setleds -D -num

-caps: Turns off caps lock light

+caps: Turn on caps lock light

-scroll: Turn off the scroll lock light

+scroll: Turn on the scroll lock light

See the setleds manual for more information and options man setleds.

4, zenity command

The zenity command displays the GTK+ dialog and returns user input. It allows you to use various shell scripts to present or request information to users. The following is an example of a GUI client who specifies the domain directory service for whois.

#!/bin/bash

# Get domain name

_zenity="/usr/bin/zenity"

_out="/tmp/whois.output.$$"

Domain=$(${_zenity} --title "Enter domain" \

--entry --text "Enter the domain you would like to see whois info" )

If [ $? -eq 0 ]

Then

# Display a progress dialog while searching whois database

Whois $domain | tee >(${_zenity} --width=200 --height=100 \

--title="whois" --progress \

--pulsate --text="Searching domain info..." \

--auto-kill --auto-close \

--percentage=10) >${_out}

# Display back output

${_zenity} --width=800 --height=600 \

--title "Whois info for $domain" \

--text-info --filename="${_out}"

Else

${_zenity} --error \

--text="No input provided"

Fi

Sample output:

Zenity: Linux / UNIX display Dialogs Boxes From The Shell Scripts

See the manual for more zenity information and other components that support GTK+:

Zenity --help

Man zenity

5, kdialog command

The kdialog command is similar to zenity, but it is designed for KDE desktop and QT applications. You can use the kdialog display dialog. The following example will display information on the screen:

Kdialog --dontagain myscript:nofilemsg --msgbox "File: '~/.backup/config' not found."

Sample output:

Kdialog: Suppressing the display of a dialog

6, Dialog

Dialog is an application that uses a shell script to display the text of a user interface component. It uses curses or ncurses libraries. Here is a sample code:

#!/bin/bash

Dialog --title "Delete file" \

--backtitle "Linux Shell Script Tutorial Example" \

--yesno "Are you sure you want to permanently delete \"/tmp/foo.txt\"?" 7 60

# Get exit status

# 0 means user hit [yes] button.

# 1 means user hit [no] button.

# 255 means user hit [Esc] key.

Response=$?

Case $response in

0) echo "File deleted.";;

1) echo "File not deleted.";;

255) echo "[ESC] key pressed.";;

Esac

See the dialog manual for details: man dialog.

Notes on other user interface tools

UNIX, Linux provides a number of other tools to display and control applications on the command line. Shell scripts can use a number of KDE, Gnome, and X component sets:

Gmessage - Clone based on GTK xmessage

Xmessage - Display or query message in window (X-based /bin/echo)

Whiptail - Display dialog from shell script

Python-dialog - Python module for making simple text or console mode user interfaces

7, logger command

The logger command writes information to the system log file, such as: /var/log/messages. It provides a shell command line interface to the syslog module syslog:

Logger "MySQL database backup failed."

Tail -f /var/log/messages

Logger -t mysqld -p daemon.error "Database Server failed"

Tail -f /var/log/syslog

Sample output:

Apr 20 00:11:45 vivek-desktop kernel: [38600.515354] CPU0: Temperature/speed normal

Apr 20 00:12:20 vivek-desktop mysqld: Database Server failed

See the logger manual for details: man logger

8, setterm command

The setterm command sets different terminal attributes. The following sample code will force the screen to go dark after 15 minutes and the monitor will stand by after 60 minutes.

Setterm -blank 15 -powersave powerdown -powerdown 60

The following example shows the text in the xterm window underlined:

Setterm -underline on;

Echo "Add Your Important Message Here"

Setterm -underline off

Another useful option is to turn the cursor display on or off:

Setterm -cursor off

Turn on the cursor:

Setterm -cursor on

See the setterm command manual for details: man setterm

9, smbclient: send messages to the MS-Windows workstation

The smbclient command can communicate with the SMB/CIFS server. It can send messages to selected or all users on the MS-Windows system.

Smbclient -M WinXPPro <

Message 1

Message 2

...

..

EOF

or

Echo "${Message}" | smbclient -M salesguy2

See the smbclient manual: man smbclient

10, Bash socket programming

Under bash, you can open a socket and send data through it. You don't have to use curl or lynx commands to grab remote server data. Bash and two special device files can be used to open a network socket. The following is selected from the bash manual:

/dev/tcp/host/port - If host is a valid hostname or network address and the port is an integer or service name, bash will attempt to open a corresponding TCP connection socket.

/dev/udp/host/port - If host is a valid host name or network address and the port is an integer or service name, bash will attempt to open a corresponding UDP connection socket.

You can use this technique to determine if a local or remote server port is open or closed without using nmap or other port scanners.

# find out if TCP port 25 open or not

(echo >/dev/tcp/localhost/25) &>/dev/null && echo "TCP port 25 open" || echo "TCP port 25 close"

The following code snippet, you can use the bash loop to find out which ports have been opened:

Echo "Scanning TCP ports..."

For p in {1..1023}

Do

(echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open"

Done

Sample output:

Scanning TCP ports...

22 open

53 open

80 open

139 open

445 open

631 open

In the following example, your bash script will work like an HTTP client:

#!/bin/bash

Exec 3<> /dev/tcp/${1:-}/80

Printf "GET / HTTP/1.0" >&3

Printf "Accept: text/html, text/plain" >&3

Printf "Accept-Language: en" >&3

Printf "User-Agent: nixCraft_BashScript v.%s" "${BASH_VERSION}" >&3

Printf "" >&3

While read LINE <&3

Do

# do something on $LINE

# or send $LINE to grep or awk for grabbing data

# or simply display back data with echo command

Echo $LINE

Done

See the bash manual for more information: man bash

Notes on GUI Tools and cron Tasks

If you use crontab to start your script, you need to use the export DISPLAY=[user machine]:0 command to request a local display or output service. For example, call /home/vivek/scripts/monitor.stock.sh with the zenity tool:

@hourly DISPLAY=:0.0 /home/vivek/scripts/monitor.stock.sh

Do you have a favorite UNIX tool that can increase the fun of shell scripts? Please share it in the comment section below.

See Through Display

Kindwin Technology (H.K.) Limited , https://www.szktlled.com