Shell Scripts

Variables

To separare variable from the rest of the text, use {}

 $ echo ${name}7

To remove a variable $name

 $ unset $name

To assign a result of a command to a variable

 $NAME=`whoami`
       or
 $NAME=$(whoami)

Standard I/O Redirection

To send the stdout and stderr to two separate files

 $ prog >file1 2>file2

To send both stdout and stderr to the same file

 $ prog >file 2>&1 

To pipe stdout and stterr of prog1 to stdin of of prog2

 $ prog1 |& prog2

Arithmatic in shell scripts

To add $a and $b

 $ let c=$a+$b; echo $c
          or
 $ c=$(( a+b )) ; echo $c
          or
 $ echo $a+$b | bc
          or
 $ expr $a + $b

 $ expr 2 \* 2

Assign the variable value to another variable
eval reads its arguments as input to the shell and executes the resulting command(s). This is usually used to execute commands generated as the result of command or variable substitution.

 i.e unmount.ksh
 #!/bin/ksh
 #usage $0 [ MYHOME | MYDATA | MYLOG ]
 UMOUNT=$1
 MYHOME="/u01/myhome"
 MYDATA="/u01/mydata"
 MYLOG="/u01/mylog"
  eval MNTDIR=\$(UMOUNT}
 /usr/sbin/umount $MNTDIR

Array Variables

In ksh, the syntax is

 set -A name value1 value2 ... valueN

In Bash

 name=(value1 ... valueN)

Array variables can be accessed as follows

 ${name[index]}

example:

 $ set -A address 404 'Broadway st' dublin ca

 $ echo ${address[0]}
   404

 $ echo ${address[1]}
   Broadway st

 $ echo ${address[2]}
   dublin

Using read to get user input for a variable value, also to prompt the user for input

 read user_name?" Please enter the user ID (Login Name) to add: "
 Please enter the user ID (Login Name) to add: 

Testing

Test command can perform tests on numeric and string data as well as on files. The test command can be used in explicit or implicit mode.

Test in explicit mode

 $ test "ABC" = "abc"

Test in implicit mode

 $ [ "ABC" = "abc" ]

Test result of command execution using "if" directly instead of using $?

  if ! diff $TMPFILE_old $TMPFILE_new > /dev/null ; then
  ........
  ........
  fi

Testing Numeric Values

 -e        Equality check
 -ne       Not equal 
 -lt       Less than 
 -gt       Greater than 
 -le       Less than or eqaul to 
 -ge       greater than or equal to 

Testing String Values

 -z string           True if string length is zero
 -n string           True if string lenth is non zero
 string1 = string2   True if string1 and string2 are equal
 string1 != string2  True if string1 is not equal to string2

Testing Files

 -d file          True if file is a directory
 -f file          True if file exists and not directory
 -s file          True if file is more than 0 bytes in length
 -r file          True if file is readable
 -w file          True if file is writable
 -x file          True if file is executable
 -L file          True if file is symbolic link
 file1 -nt file2  True if file is newer than file2

Loop

While loop

cat "filename" | while read data
do
.......
.......
done

case function

 case  $variable-name  in
                pattern1)   command
                            ...
                            command;;
                *)          command
                            ...
                            command;;
           esac

Breaking the loop

The break command discontinues the execution of loop immediately and transferes control to the command following the done keyword. You can pass a number n as an aargument to the break command. In that case, the break command jumps to the command after the nth occurrence of the done keyword.

Continue command

The continue skips the remaining part of the loop and transfer the control to the start of the loop for the next iteration.

Functions

To define function

 function_name ()
 {
 ......
 ......
 }

To process multiple options


Use getopts internal command to process mutiple options in a shell scripts

 while getopts ":ab:c" opt; do
    case $opt in 
	a  ) process option -a ;;
	b  ) process option -b 
	     $OPTARG is the option's argument ;;
	c  ) process option -c ;;
	\? ) print 'usage: bob [-a] [-b barg] [-c] args...'
	     return 1
    esac
 done
 shift $(($OPTIND - 1))

 normal processing of arguments...
  • Its first argument is a string containing all valid option letters. If an option requires an argument, a colon follows its letter in the string. An initial colon causes getopts not to print an error message when the user gives an invalid option.
  • Its second argument is the name of a variable that will hold each option letter (without any leading dash) as it is processed.
  • If an option takes an argument, the argument is stored in the variable OPTARG.
  • The variable OPTIND contains a number equal to the next command-line argument to be processed. After getopts is done, it equals the number of the first "real" argument.

Tips

In the bash shell, to enable interpretation of backslash escapes, use the -e option

 $ echo -e "this is a test line \n"

basename is a standard UNIX computer program, when basename is given a pathname, it will delete any prefix up to the last slash ('/') character and return the result. basename is described in the Single UNIX Specification and is a primarily used in shell scripts.

 # basename /home/user1/test.sh
 test.sh

dirname delivers all but the last level of the path name in string

 # dirname /usr/local/bin
 /usr/local

trap

 trap "" 1 2 3
 trap 'clear' 2  # clear screen when break signal is sent
 trap - 2  ## To undo the trap

TMOUT variable
It is used to set auto time out variable the ksh or posix compliant shell. The TMOUT value is defined in seconds. We can define the following lines /etc/profile to make users not to change these values

 TMOUT=600 
 export TMOUT
 readonly TMOUT

In C-Shell autologout variable is used instead of TOMOUT. Define "set autologout=1200" in /etc/csh.login file

'''set options"

 set -n   # Reads commands but does not execute them
 set -f   # disable wildcard filename expansion (globbing) 
 set -e   # Exits the program if a command returns a nonzero value
 set -x   # echo line to stderr before executing it