Shell programming - schoolmca
Shell Programming
It includes the entire gamut of unix command command with syntax of programming language called shell programming.
Shell programming perspective
Shell forms an interface between user and the system.
Incorporates a powerful programming language that enables the user to exploit the full power and versatility of unix.
File that contains collection of valid unix commands along with the construct of the programming language is called shell script or shell programming.
Relationship of shell to unix
Different shells available in unix:-
• Bourne shell
• Bash shell
• Korn shell
• C shell
Description:-
|Shell |Creator |Prompt |
|Bourne |Steave Bourne of AT & T Bell. |$ |
|Bash |Brain Fox & chet Ramey |$ |
|Korn |David Korn |$ |
|C shell |Bill Joy.developed at university of california. |% |
FEATURES OF SHELL:-
1) COMMAND EXECUTION:- $who
2) FILE NAME SUBSTITUTION:- $ls ?
3) IO REDIRECTION
4) PIPE LINE MECHANISM
5) ENVIRONMENT CONTROL
6) INTERPRETING PROGRAMMING LANGUAGE
FOR KNOWING THE CURRENT WORKING SHELL:-
$echo $SHELL
for bourne shell- /bin/sh or /bin/bsh
for korn shell- /bin/ksh
for bash shell- /bin/bash
to change the shell:-
$echo $SHELL
/bin/sh
$ksh
$echo $SHELL
/bin/ksh
$^d /* this wil take you out from current working shell */
creating a shell script:
$vi test
compilation + execution
$ sh
no object file is created .Shell script need no extention(not mendatory)
another way to execute is changemod ,give execution permission
and then execute.
$ chmod 700
$ test
sh :-execution of the shell script is done with the help of sh command as a newly borned script you have only read and write permission turn on where as execute permission is turn off..thus shell script can be invoked in either of the two ways:-
1) invoking the sh command with file name as argument .
2) making the shell script executable by changing its excess permission and then invoking the file.
Unix system variables:-
These variables are a part of unix system and can not be altered .
1) PS1:- stands for system prompt 1.
$ echo $ PS1
$
$ PS1 = “#”
#
2) PS2:- system prompt 2 that is secondary prompt
$ echo $ PS2
>
$
3) PATH:- defines the path which the shell must search in order to execute any command or file
$ echo PATH.
/usr/local/bin:/usr/bin:/bin:/usr/bin/x11:/usr/games.
4) HOME:- store the default working directory of the user.
$ echo $ HOME
/*assume that your register number is your login name*/
/usr/ 1pi02mca09
5) LOGNAME:- stores the login name of the user
$ echo $ LOGNAME
ngp
$
6) MAIL:- defines the file along with the path where the name of the user is stored
/usr/MAIL/ngp
7) MAILCHECK :- defines the duration after which yhe shell checks wether the user has recieved any mail
$ echo $ MAILCHECK
60
$
8) SHELL:- defines the name of your working shell.
9) TERM :- defines the name of the terminal on which you are working
$ echo $ TERM
ansi
$
10) TZ:- defines the name of the time zone on which you are working .
User defined variables:-
The variables can constitute alphabets,digits and underscores .However the first character must be either an alphabet or an underscore
Example:-
$ a=10
$ echo $a
10
$
tips and traps:-
1)All shell variables are string variables .
Example:- in A=10,where 10 is stored in A ,is not treated as a number but as a string of characters 1 and 0.Naturally we can not perform any arithmatic operations.
2) Variables may contain more than one word in which case it should be enclosed in “ ”
Example:-
$a = “Hello world”
$echo $ a
Hello world
$
3) We can carry out more than 1 assignment in a single line.
Example:-
$name = abc age = 5
$echo $name $age
abc 5
$
4) A variable may not be given any value.They are called as NULL variables.A NULL
variable can be treated in any 1 of the follwing ways:-
$d = “”
OR
$d = ‘’
OR
$d
5) I/O operations in the shell:-
The output operation is performed with the help of echo statement,whereas the input is
performed with the help of read statement.
Question:-
Write a shell script to accept a number and display.
Answer:-
echo “enter the numbers”
read num
echo “u entered $num”
VARIABLES:-
3 basic type of variables available:-
1) POSITIONAL PARAMETERS:- invoked by normal shell variables.It is called as
positional parameter or postional variables depending upon the position it occupies
during the execution stage.
EXAMPLE:-
echo “my name is $1”
echo “your name is $2”
$sh test abc xyz
OUTPUT:-
my name is abc
your name is xyz
NOTE:- Shell can take a maximum a maximum of a positional parameter.
2)SPECIAL PARAMETER:- There are 2 types of special parameters:-
a) $# :- returns the number of arguments.
echo “the total number of arguments specified is $#”
EXAMPLE:-
sh test learning unix
OUTPUT:-
the total number of arguments specified is 2
$
b) $* :- Returns all the arguments
EXAMPLE:-
echo “argument are $*”
$sh test learning unix
HOW ABOUT THIS :-
$cat > name_test
echo “enter the name”
read name
echo “enter the telephone number”
read number
echo $name $number >> mylist
+d
$sh name_test
OUTPUT:-
enter the name
charul
enter the telephone number
234256
$
now type we write :-
$cat my_list
charul
234256
ARITHMETIC OPERATORS & EXPRESSION:-
Arithmetic operators supported are:-
+ : addition
- : subtraction
* : multiplication
/ : division
In order to perform arithmetic operations we need to make use of ‘expr’ command
a = 5
b = 10
c = `expr $a + $b`
echo $c
For multiplication :-
$expr 5 \* 2
10
DECISION CONTROL STATEMENTS:-
If-fi structure:-
Syntax:-
if []
then
statements
else
statements
fi
There are 3 test can be performed:-
1)Test on numerical values :- Carried on with the help of what is called a relational operator.
|Relational operator |Meaning |
|-eq |Equal to |
|-ne |Not equal to |
|-gt |Greater than |
|-ge |Greater than or equal to |
|-lt |Less than |
|-le |Less than or equal to |
QUESTION :-
Write a shell script to accept a number and check whether it is greater than 10 or not
echo “enter the number”
read num
if [$num –gt 10]
then
echo “number is greater than 10”
else
echo “number is less than 10”
fi
QUESTION :-
Write a script to display total number of users currently working.
users = `who|wc-l`
if [$users – eq 1]
then
echo “ u r the only person working on”
else
echo $users are working
fi
2)Test on character strings :-
The operators used are equal ‘=’ and ‘!=’
QUESTION :-
Write a shell script to check whether your current working directory is same as home
directory.
x = `pwd`
if [ “$x” = “HOME”]
then
echo “u r working in home directory”
else
echo “u r not working in home directory”
fi
3)Test on file types:-
It is concerned with the existence of the file and it’s property.The following operators are used.
|Operators |Meaning |
|-s |Check that file exists & not empty |
|-f |Check that file is an ordinary file |
|-d |Check whether file is directory |
|-w |Check that file is writeable |
|-r |Check that file is readable |
|-x |Check that file is executable |
QUESTION :-
Write a shell script to accept a file name and check whether it is executable or not,if not make it executable
echo “enter the filename”
read fname
if [-x $fname]
then
echo “file $fname is executable”
else
chmod 700 $fname
fi
SAMPLE OUTPUT :-
$sh test
enter the filename
prg1
$ls –l prg1
-rwx……
SHELL SCRIPT EXAMPLES :
1. Write a shell script which will accept a filename and starting and ending line numbers and displays these lines from given file.
2. Two numbers are entered from keyboard. Write a script to find the value of one number raised to power of another.
3. Write a shell script which deletes all lines containing the word unix in the files supplied as arguments.
4. Write a shell script which displays a list of all the files in the current directory to which you have read, write and execute permissions.
5. A shell script receives even number of filenames as arguments. Suppose four files are supplied as an arguments, then the first file should get copied into second, third file into fourth and so on. If odd number of filenames are supplied then no copying should take place and an error message should be displayed.
6. Write a shell script which will receive any number of filenames as arguments. The shell script should check whether every argument supplied is a file or a directory. If it a directory it should be appropriately reported. If it is a filename then name of the file as well as the number of lines present in it should be reported.
7. Write a shell script which gets executed the moment the user logs in. It should display the message, “ Good Morning”, “ Good Afternoon”, “ Good Evening”, depending upon the time at which the user logs in.
8. Write a shell script which will receive login name during execution, obtain information about it from /etc/passwd and display this information on screen in easily understandable format.
9. While executing a shell script either login name or UID is supplied at command prompt. Write a shell script to find out at how many terminals has this user logged in.
10. Write a shell script which reports names and sizes of all files in a directory ( directory name would be supplied as an argument ) whose size exceeds 1000 bytes. The filenames should be printed in descending order of their sizes. The total number of such files should also be displayed.
11. A friend of yours has promised to log in at a particular time. However he has not kept the promise. You want to contact him as soon as he logs in. Write a shell script which checks after every one minute whether your friend has logged in or not. The logname should be supplied at command prompt.
12. Write a shell script to send mail to groups of users by extracting their IDs from /etc/group file.
13. A file called wordfile consists of several words. Write a shell script which will receive a list of filenames, the first of which would be wordfile. The shell script should report all occurrences of each word in wordfile in the rest of the files supplied as arguments.
14. The word unix is present in only some of the files supplied as arguments to this shell script. Your shell script should search each of these files in turn and stop at the first file that it encounters containing the word unix. The filename should be displayed on the screen.
15. Write a shell script which will receive any number of filenames as arguments. The shell script should check whether such files already exists. If they do, then they should be reported. If any of these files do not exist then check if a sub directory called mydir exists in the current directory. If it doesn’t exist then it should be created and in it the files supplied as an arguments should be created. If mydir already exists then it should be reported along with the number of files that are currently present in mydir.
16. Write a shell script to determine how long a user has been working on the system.
17. Write a shell script which accepts any number of arguments and prints them in reverse order. Ex : If file name is test then $ sh test A B C should produce C B A.
18. Write a shell script that accepts a path name and creates all the components in that path name as directories. For example if the file name is test then : $ sh test a/b/c/d should create directories a, a/b, a/b/c, a/b/c/d.
19. Write a shell script to implement terminal locking ( similar to lock command ), it should prompt for a password. After accepting the password entered by the user, it must prompt again for the matching password as confirmation and if the match occurs, it must lock the keyboard, until a matching password is entered again. Your script should take care of disregarding break, control-d etc. No time limit need be implemented for the lock duration.
20. Write a shell script that finds and displays all the links to a file specified as the first argument to the script. The second argument which is optional can be used to specify the directory in which the search to begin. If this second argument is not present the search is to begin in the current directory. In either case the starting directory as well as all its sub directories at all levels must be searched.
21. Write a shell script to display the calendar for current month with current date replaced by * or ** depending on whether the date is single digit or two digits.
Shell scripts:-
1. write a shell script to accept a number and check wether it is greater than 10 or not.
ANS:
echo “Enter the number”
read num
if [$ num -gt 10]
then
echo “ number is greater than 10”
else
echo “numbe is less than 10”
fi
2. write a shell script to find the number of users currently working.
ANS:
User=`who|wc-l`
If [$ user –eq 1]
then
echo “ u are the only user”
else
echo “ $user user are working”
3. write a shell script to accept a filename and check wether it is executable or not if not make executable.
ANS:
echo “enter the filename”
read fname
if [-x $fname]
then
echo “file $fname is executable”
else
chmod 700 $fname
fi
4. write a script using while loop to print from 1 to 10.
ANS:
While[$num-le 10]
do
echo $num
i=`expr $i + 1`
done
5. write a shell script to check wether ur current working directory is same as home directory.
ANS:
pwd1=`pwd`
if [`$pwd1=$HOME`]
then
echo “you r working in ur home directory”
else
echo “ you are not in ur home directory”
6. create a unix command menu using case.
ANS:
echo “unix command menu”
echo 1: list of files
echo 2: long list of files
echo 3: current working directory
echo 4: list of users
echo “enter your choice”
read choice
case $choice in
1) ls;;
2) ls-l;;
3) pwd;;
4) who;;
7. write a shell script which will accept any number of filename as argumants. The script should check wether every argument supplied is either a file of directory. If it is a directory, it should be reported otherwise it will display the total number of line contained in that file.
ANS:
for i in $*
do
if[-d $i]
then
echo “directory $i”
else
echo “file $i contains`cat $i|wc-l` line”
fi
done
8. write a shell script to search the phone number given the name from the file phone.lst containing fields name, address and phone number.
ANS:
echo “enter the name”
read name
phone = grep “^$name” phone.lst | cut-d “:” f3
echo $phone
9. write a shell script to count the number of vowels in a string.
ANS:
echo “enter the string”
read str
i=1
count=0
len = `expr length $str`
while [$i –le $len]
do
char = `echo $str | cut –c$i`
case $char in
a|e|i|o|u) count = `expr $count + 1`;;
esac
i=`expr $i +1`
done
echo $count
10. write a schell script to find out wether the user whose login name passed as parameter is currently logged in or not. If the user has logged in send the file Hello available in your pwd to his terminal.
ANS:
Clear
If who|grep $1
then
terminal = `who | grep $1 | tr-s “ “ “:” | cut-d “:” -f2
cat hello > /dev/$terminal
11. write a shell script to reverse a string
ANS:
Clear
len = `expr length $str`
count=1
while [$len –ge $count]
do
char = `echo $1 | cut –c $len
rev = $rev$char
len = `expr len-1`
done
echo “the reversr string is $rev”
12. write a shell script that accepts two filename as arguments. Check if the permissions of these are identical and if they are identical, output permission otherwise o/p each filename with its permission.
ANS:
file1p = `ls-l $1| tr –s “ “ “:” | cut –c2-4`
file2p = `ls-l $2| tr –s “ “ “:” | cut –c2-4`
if [“$file1p” = “$file2p”]
then
echo “common permissions $file1p
else
echo “file $1 has $file1p permission
echo “file $2 has $file2p permission
13. write a shell script which reports name and size of the files in the directory [dirctory name specified as argument] whose size exceeds 1000 bytes. Filenames should be printed in descending order of their sizes. Total number of files should be reported.
ANS:
Clear
if [$# -ne 1]
then
echo “Improper term”
exit
fi
if [! –d$1]
then
echo “$1 is not a directory”
exit
fi
cd $1 rm temp
for i in *
do
size = `ls-l $i | tr-s “ “ “:” | cut –d “:” –f5`
if [$ size –gt 1000]
then
fname = `ls-l $i | tr-s “ “ “:” | cut –d “:” –f10`
echo $fname “:” $size >>temp
fi
done
sort-t “:” +1nr temp
echo total number of files is `cat emp | wc-l`
exit
14. write a shell script called WHERE AM i when invoked, it should point out the users name. The host name of the current machine, full path, name of the current working directory, current date and lists the contents of current directory.
ANS:
echo “the username is” `who am i`
echo “the host name is” `uname`
echo “the current workin directory” `PATH`
echo “the current data is” `date`
echo “the files in the directory is” `ls`
-----------------------
The shell
you
Unix kernel
Shell accepts command from you
Translate result s back to you
Translates to binary code
Shell reads results from kernel kernel
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- royal dutch shell yahoo finance
- unix shell for windows 10
- call shell script in python
- ubuntu shell for windows 10
- how to run a shell script
- how to run shell script in cmd
- command to execute shell script
- bash shell commands list
- linux shell cheat sheet
- bash shell tutorial
- running shell scripts in windows
- linux execute shell script