Basic Shell Programming
First we will create a text file which contains the text as below,
[root@localhost root]# cat > f1
who
date
cal
^D
Now we have to give the executive permission to the file “f1”,
[root@localhost root]# chmod u+x f1
[root@localhost root]# ls -l f1
-rwx-w-r-- root root 24 22 May 2004 f1
Now, we can execute this file by giving command as below,
[root@localhost root]# ./f1
ð It will display all users along with terminals which are running, current date and time and calendar of the current month. That means the contents of the file works as command.
"echo" is a function of bash shell which prints a given string on the monitor screen.
Example,
[root@localhost root]# echo “Linux is a OS”
Linux is a OS
[root@localhost root]# echo *
ð It will display all files’ name of current directory. If we want to display only a character of star "*", then we execute the command as below,
[root@localhost root]# echo \*
Or
[root@localhost root]# echo '*'
*
The shell commands also can be performed through the echo command.
Example,
[root@localhost root]# echo `date`
Tue Jun 7 13:44:10 BDT 2005
ð It will show the current date.
[root@localhost root]# echo `cal`
June 2005
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
ð It shows the calendar of current month.
To show the text of “date” or “cal” or “ls” etc on the monitor screen by echo command, then we can execute the command as below,
[root@localhost root]# echo date
date
[root@localhost root]# echo cal
cal
[root@localhost root]# echo ls
ls
We can use a variable in shell programming.
Example,
[root@localhost root]# new_var=5987
[root@localhost root]# echo $new_var
5987
ð Here new_var is an integer variable and its value is 5987 which is displayed on the monitor by echo command.
Some examples of shell programming are given below,
[root@localhost root]# cat > Math.sh
a=3
b=6
a=`expr $a '*' $b`
echo $a
[root@localhost root]# ./Math.sh
18
[root@localhost root]# cat > add.sh
a=5
b=5
a=`expr $a + $b`
echo The addition of A+B = $a
[root@localhost root]# ./Math.sh
The addition of A+B = 10
The bash shell and configuration
The shell is configured through a variety of mechanisms.
1. Local variables
2. Aliases and functions.
3. The set and shopt commands.
Variables
A variable is a label that has a value. Display variables and value using:
· set command to display all variables.
· env command to display environment variables.
· echo command to display value of a given variable.
Example,
The set, env and echo commands can be used to display all variables, environment variables and a single variable value, respectively.
[root@localhost root]# set | less
[root@localhost root]# env |less
[root@localhost root]# echo $HOME
Configuring the Shell (local variables)
Data is shell script and environment settings stored in variables.
Setting variable value: VARIABLE = VALUE
Examples,
[root@localhost root]# FAV_COLOR=blue
To retrieve variable value, use $before variable name,
[root@localhost root]# echo $FAV_COLOR
blue
[root@localhost root]# WELCOME=”Welcome to Red Hat”
[root@localhost root]# echo $WELCOME
Welcome to Red Hat
There are some common Local Variables which are used by shell:
HISTFILESIZE | Determines how many commands to be saved in the history file on logout. |
COLUMNS | Sets the width of the terminal. |
LINES | Sets the height of the terminal. |
HISTFILE | Specifies the file in which history commands are stored on logout. |
HISTSIZE | Specifies the number of history commands to keep while operating interactively. |
Other Shell Configuration
Less common, but powerful commands to configure elements of the shell are,
1. set
2. shopt
Example: The set command can configure many different aspects of the shell. Such as:
Command | Performance |
set -b | Respect terminal of background commands immediately rather than waiting for next prompt. |
set –u | Unset variables generate an error. |
set –o noclobber | Do not clobber files with > and > & operators. |
set –o vi | Use vi syntax on bash command line instead of default emacs system. |
Configuring commands (Environment Variables)
Shell variables exist only in current shell instance but Environment variables passed to sub-shells. Shell variables can be exported into environment.
Example,
$EDITOR=/user/bin/vim; export EDITOR
Common environment variables: | |
HOME | Path to user’s home directory. |
LANG | Identification of default language programs should use; example: en_us, UTF-8 for U.S. English. |
PWD | User’s current working directory. |
EDITOR | Default editor programs should invoke for text editing. |
LESS | Operations to pass to the less command. |
The term environment variable: | |
TERM | Environment variable setting the terminal type. |
reset | Command (not variable) used to reset a terminal should the screen be come corrupted. |
You can change the shell’s style by the PS1 command,
[root@localhost root]# PS1="Enter you command # "
Enter you command # ls
ð It shows the command prompt in different style.
Some important option of PS1 (or the PS1 local variable) is given below:
\u - Display user name.
\h - Display Hostname.
\W - Display Current Directory.
\t - Display Current Time.
\d - Display Current Date.
\! -
\$ - Display for Normal User.
\# - Display for Super User.
Example,
Enter you command # PS1="[\u@\h \W]#"
[root@localhost root]#
MOTD
You can send message of the day to a user when h/she will login the system. The message are stored in the file is called /etc/motd.
[root@localhost root]# cat > /etc/motd
Welcome In Linux.
ð This message will display when user login the system.
You can execute some Linux command, when any user is going to logout the system. The command is written in the file called .bash_logout. This file is hidden and stored in every user's home directory.
[root@localhost root]# cat > .bash_logout
cal
date
ð The cal and date command will be executed at logout time.
You can give one or more alias names to a command. Example, d is a new alias name of ls -l and it will execute as like ls –l command.
[root@localhost root]# alias d='ls -l'
[root@localhost root]# d
ð It will show all files and directories from /root directory.
All alias names of commands are usually stored in the file called bashrc which is stored in every user's home directory and it is a hidden file.
[root@localhost root]# vi /root/.bashrc
# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias mcdrom='mount /mnt/cdrom'
alias ucdrom='umount /mnt/cdrom'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
Again there is another bashrc file in /etc directory. If you write any alias name of command in this file, every user can use that alias name.
[root@localhost root]# vi /etc/bashrc
# /etc/bashrc
# System wide functions and aliases
# Environment stuff goes in /etc/profile
# by default, we want this to get set.
# Even for non-interactive, non-login shells.
if [ "`id -gn`" = "`id -un`" -a `id -u` -gt 99 ]; then
umask 002
else
umask 022
fi
# are we an interactive shell?
if [ "$PS1" ]; then
case $TERM in
xterm*)
if [ -e /etc/sysconfig/bash-prompt-xterm ]; then
PROMPT_COMMAND=/etc/sysconfig/bash-prompt-xterm
else
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\007"'
fi
;;
screen)
if [ -e /etc/sysconfig/bash-prompt-screen ]; then
PROMPT_COMMAND=/etc/sysconfig/bash-prompt-screen
else
PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\033\\"'
fi
;;
*)
[ -e /etc/sysconfig/bash-prompt-default ] && PROMPT_COMMAND=/etc/sysconfig/bash-prompt-default
;;
esac
# Turn on checkwinsize
shopt -s checkwinsize
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ "
if [ "x$SHLVL" != "x1" ]; then # We're not a login shell
for i in /etc/profile.d/*.sh; do
if [ -r "$i" ]; then
. $i
fi
done
unset i
fi
fi
# vim:ts=4:sw=4
ð This file contains some important data, such as, the value of umask, PS1 etc.
[root@localhost root]# alias
alias cdrom='cd /mnt/cdrom/Fedora/RPMS'
alias cp='cp -i'
alias floppy='mount /mnt/floppy'
alias l.='ls -d .* --color=tty'
alias ll='ls -l --color=tty'
alias ls='ls --color=tty'
alias mc='. /usr/share/mc/bin/mc-wrapper.sh'
alias mcdrom='mount /mnt/cdrom'
alias mv='mv -i'
alias rm='rm -i'
alias ucdrom='umount /mnt/cdrom'
alias ufloppy='umount /mnt/floppy'
alias vi='vim'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
ð It shows all alias names which can be executed as command.
[root@localhost root]# unalias
Example,
[root@localhost root]# unalias d
ð To delete the alias name.
Anchors
Anchors match the beginning or end of a line or word,
Anchors Symbol | Performance |
^ | Line begins with. |
$ | Line ends with. |
\< | Word begins with. |
\> | Word ends with. |
Example,
\
cat \>
\
[root@localhost root]# history
1 isapnp isapnp.conf
2 cat /proc/interrupts
3 cat /proc/ioports
4 cat /proc/dma
5 cat /proc/pci
6 service sound start
7 rc.d/init.d/sound start
8 dmesg |grep *cry*
9 dmesg |grep *cr*
10 dmesg |grep *c*
11 dmesg |grep *Cr*
12 dmesg |grep *isa*
ð It shows all commands which are used before in command prompt.
[root@localhost root]# echo $HISTORYSIZE
1000
ð It shows the history size. That means how many commands can be stored in /etc/history file. We can change the history size by editing /etc/profile file.
[root@localhost root]# vi /etc/profile
# /etc/profile
# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc
pathmunge () {
if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
fi
}
# Path manipulation
if [ `id -u` = 0 ]; then
pathmunge /sbin
pathmunge /usr/sbin
pathmunge /usr/local/sbin
fi
pathmunge /usr/X11R6/bin after
unset pathmunge
# No core files by default
ulimit -S -c 0 > /dev/null 2>&1
USER="`id -un`"
LOGNAME=$USER
MAIL="/var/spool/mail/$USER"
HOSTNAME=`/bin/hostname`
HISTSIZE=1000
if [ -z "$INPUTRC" -a ! -f "$HOME/.inputrc" ]; then
INPUTRC=/etc/inputrc
fi
export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC
for i in /etc/profile.d/*.sh ; do
if [ -r "$i" ]; then
. $i
fi
done
unset i
ð This file contains some important data, such as, the value of history size etc.
[root@localhost root]# vi /etc/DIR_COLORS
# Configuration file for the color ls utility
# This file goes in the /etc directory, and must be world readable.
# You can copy this file to .dir_colors in your $HOME directory to #override
# the system defaults.
# COLOR needs one of these arguments: 'tty' colorizes output to ttys, #but not
# pipes. 'all' adds color characters to all output. 'none' shuts #colorization
# off.
COLOR tty
# Extra command line options for ls go here.
# Basically these ones are:
# -F = show '/' for dirs, '*' for executables, etc.
# -T 0 = don't trust tab spacing when formatting ls output.
OPTIONS -F -T 0
# Below, there should be one TERM entry for each termtype that is #colorizable
TERM linux
TERM console
TERM con132x25
TERM con132x30
TERM con132x43
TERM con132x60
TERM con80x25
TERM con80x28
TERM con80x30
TERM con80x43
TERM con80x50
TERM con80x60
TERM cons25
TERM xterm
TERM rxvt
TERM xterm-color
TERM color-xterm
TERM vt100
TERM dtterm
TERM color_xterm
TERM ansi
TERM screen
TERM kon
TERM kterm
# EIGHTBIT, followed by '1' for on, '0' for off. (8-bit output)
EIGHTBIT 1
# Below are the color init strings for the basic file types. A color #init
# string consists of one or more of the following numeric codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan #37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan #47=white
NORMAL 00 # global default, although everything should be something.
FILE 00 # normal file
DIR 01;34 # directory
LINK 01;36 # symbolic link
FIFO 40;33 # pipe
SOCK 01;35 # socket
BLK 40;33;01 # block device driver
CHR 40;33;01 # character device driver
ORPHAN 01;05;37;41 # orphaned syminks
MISSING 01;05;37;41 # ... and the files they point to
# This is for files with execute permission:
EXEC 01;32
# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
# (and any comments you want to add after a '#')
.cmd 01;32 # executables (bright green)
.exe 01;32
.com 01;32
.btm 01;32
.bat 01;32
.sh 01;32
.csh 01;32
.tar 01;31 # archives or compressed (bright red)
.tgz 01;31
.arj 01;31
.taz 01;31
.lzh 01;31
.zip 01;31
.z 01;31
.Z 01;31
.gz 01;31
.bz2 01;31
.bz 01;31
.tz 01;31
.rpm 01;31
.cpio 01;31
.jpg 01;35 # image formats
.gif 01;35
.bmp 01;35
.xbm 01;35
.xpm 01;35
.png 01;35
.tif 01;35
ð This file contains the setting of color of director file, ordinary file, tar file, zip file etc.
Relational condition of shell programming
Command Used in Shell Programming | Meaning |
-gt | > |
-ge | >= |
-eq | = |
-le | <= |
-lt | < |
-ne | != |
Conditional Statement
Syntax: | Example |
if [ condition ] then statement fi | a=5 f [ $a -eq 5 ] then echo A is equal to 5 fi |
Syntax: | Example |
if [ condition ] then statement statement else statement fi | a=3 b=5 f [ $a -gt $b ] then echo A is greater then B else echo B is greater then A fi |
LOOPING CONDITION
Syntax: | Example |
while [ condition ] do statement increment done | a=1 b=10 while [ $a -le $b ] do echo $a a=`expr $a + 1` done |
Syntax: | Example |
until [ condition is false ] do statement increment done | a=1 b=10 while [ $a -eq $b ] do echo $a a=`expr $a + 1` done |
FOR LOOPING
Syntax: | Example |
for variable in arg1 arg2 arg3 .. .. .. .. do statement done | for var in 1 2 3 4 do c=`expr $var '*' $var` echo $var \* var = $c done |
CASE statement
Syntax: | Example |
case $var in value 1) statement ;; value 1) statement ;; value 1) statement ;; ... ... ... ... ... ... ... ... ... ... ... ... .. .... ... ... esac | echo "Enter two values : " read a b echo a b echo 1. ADD echo 2. SUB echo 3. MUL echo 4. DIV read var case $var in 1) c=`expr $a + $b` ;; 2) c=`expr $a - $b` ;; 3) c=`expr $a \* $b` ;; 5) c=`expr $a / $b` ;; esac echo Result = $c |
Another example of CASE statement:
[root@localhost root]# cat . case1.sh
echo "Enter a key: "
read a
case $a in
[a-z])
echo "You have pressed a character :"
;;
[0-9])
echo "You have pressed a number :"
;;
?)
echo "You have pressed a symbol :"
;;
*)
echo "Incorrect value."
esac
ð In the program, the value "?" means all keyboard symbol and "*" means default value.
break is a keyword, it breaks looping of the line.
Example,
i=1
while [ $i -le 10 ]
do
echo $i
i=`expr $i + 1`
if [ $i -eq 5 ]
then
break
fi
done
echo "The Looping is breaked."
EXIT statement
exit is a keyword. It can exit the whole program.
CONTINUE statement
This keyword always sends the compiler again to the looping statement.
POSITION PARAMETER
It can take the value of variable from the arguments which are given on the program executive time. The variable can declare as $1 which takes the value from first argument, $2 which takes the value from second argument, so on.
Example,
[root@localhost root]# cat > parameter.sh
echo $1 $2
c=`expr $1 + $2`
echo $c
[root@localhost root]# sh parameter.sh 4 5
4 5
9
ð The output is coming by adding of the argument 4 and 5.