10 tools to make your shell script more powerful

  sonic0002        2013-04-05 08:50:41       7,150        0    

Many people mistakenly think that shell scripts can only be run in command line. In fact shell can also call some GUI components such as menus,alert dialogs, progress bar etc. You can control the final output, cursor position and various output effects. Here we introduce some tools which can help you create powerful, interactive and user friendly Unix/Linux shell scripts.

1. notify-send

This command can let you inform the process to send a desktop notification to users. This can be used to send prompt to users or display some information to users. You can download it :

$ sudo apt-get install libnotify-bin

Below example will show how to send a simple notification:

notify-send "rsnapshot done :)" 

Here is a complex example:

....
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; }
...

Here is the explanation of the parameters:

  • -t 5000 : The timeout time in milliseconds
  • -u low : Set the urgency
  • -i gtk-dialog-info : Notification icon, you can set the icon with -i /path/to/your-icon.png

2. tput

This command is to set the terminal properties:

  • Move cursor
  • get terminal information
  • Set foreground and background color
  • Set the bold style

Example:

#!/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 "M A I N - M E N U"
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

3. setleds

This command can be used to control keyboard light. For example turn on the num lock light:

setleds -D +num

Turn off num lock light:

setleds -D -num
  • -caps : Turn off CAPS light
  • +caps: Turn on CAPS light
  • -scroll : Turn off scroll lock
  • +scroll : Turn on scroll light

4. zenity

This command can display GTK+ dialogs and return the user input. You can use this command in script to display information and ask for user input. Below codes are for domain whois search:

#!/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

5. kdialog

This command is similar to zenity, but it's for KDE/Qt applications. The usage is:

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

You can check out more information through shell scription with KDE Dialogs

6. Dialog

This command will show the text component in shell script. It uses curses and ncurses libraries. Demo codes:

>#!/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

7. logger

This command can let you write sys log such as /var/log/messages:

>#!/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

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

8. setterm

This command sets interrupt property. Below example will force the screen to be black for 15 minutes. And set the monitor in standby mode after 60 minutes:

setterm -blank 15 -powersave powerdown -powerdown 60

Below command can show text with underline:

setterm -underline on;
echo "Add Your Important Message Here"
setterm -underline off

Or you can switch off the cursor:

setterm -cursor off

9. smbclient : Send message to MS-Windows

smbclient can communicate with SMB/CIFS server, it can send message to users of MS-Windows:

smbclient -M WinXPPro <

or

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

10. Bash Socket

You can open a socket connection in bash and transfer data. Bash has two specific device files:

 /dev/tcp/host/port -- If hostname and port is legal, bash will try to establish a TCP connection

/dev/udp/host/port -- If hostname and port is legal, bash will establish a UDP connection

You can use this to test whether a host's port is open without using nmap or port scanner:

# find out if TCP port 25 open or not
(echo >/dev/tcp/localhost/25) &>/dev/null && echo "TCP port 25 open" || echo "TCP port 2

You can also

echo "Scanning TCP ports..."
for p in {1..1023}
do
  (echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open"
done

Output:

Scanning TCP ports... 
22 open 
53 open 
80 open 
139 open 
445 open 
631 open

Below codes will make your script a HTTP client:

#!/bin/bash
exec 3<> /dev/tcp/${1:-www.cyberciti.biz}/80
 
printf "GET / HTTP/1.0\r\n" >&3
printf "Accept: text/html, text/plain\r\n" >&3
printf "Accept-Language: en\r\n" >&3
printf "User-Agent: nixCraft_BashScript v.%s\r\n" "${BASH_VERSION}"   >&3
printf "\r\n" >&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

About GUITools and Cronjob

If you use cronjob to call your script, you should use "export DISPLAY=[user's machine]:0" to set local display/input service. For example calling  /home/vivek/scripts/monitor.stock.sh

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

You can use "man" to view all commands usages.

Source : http://www.oschina.net/question/28_39527

GUI  SHELL  ZENITY 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Texting in class

How to send SMS safely in class. New skill get