Linux Shell Programming Lab
Linux Shell Programming Lab
3 STANDARD PROCEDURES:
2) CLEAR:
At the terminal write the following:
[user1@com]$ clear
3) WHO:
At the terminal write the following:
[user1@com]$ who
[user1@com]$ who -q
[user1@com]$ who -H
[user1@com]$ who m
4) DATE:
At the terminal write the following:
[user1@com]$ date
[user1@com]$ date
[user1@com]$ date +%D
[user1@com]$ date +%d
[user1@com]$ date +%d%m%h
6)cat
catallows you to read multiple files and then print them out. You can combine files by
using the > operator and append files by using >>.
Syntax: cat [argument] [specific file]
Example:
cat abc.txt
If you want to append three files (abc.txt, def.txt, xyz.txt), give the command as,
cat abc.txt def.txt xyz.txt > all
7)cd, chdir
cd (or chdir)
move around your file structure.
Syntax: cd [name of directory you want to move to]
When changing directories, start with / and then type the complete file path, like
cd /vvs/abc/xyz
8)cp
The cp command copies files or directories from one place to another. You can copy a
set of files to another file, or copy one or more files under the same name in a
directory. If the destination of the file you want to copy is an existing file, then the
existing file is overwritten. If the destination is an existing directory, then the file is
copied into that directory.
Syntax: cp [options] file1 file2
If you want to copy the file favourites.html into the directory called laksh, you give
the command as:
cp favourites.html /vvs/laksh/
A handy option to use with cp is -r. This recursively copies a particular directory and
all of its contents to the sp
time.
9)grep
The grep command searches a file or files for lines that match a provided regular
globally search for a regular
expression and then print the found matches).
Syntax: grep [options] regular expression [files]
To exit this command, type 0 if lines have matched, 1 if no lines match, and 2 for
errors. This is very useful if you need to match things in several files. If you wanted to
find out which files in our vvs mca grep
to search the directory and match those files with that word. All that you have to do is
give the command as shown:
The * used in this example is called a meta-character, and it represents matching zero
10)ls
lswill list all the files in the current directory. If one or more files are given, ls will
11) mv
mv moves files and directories. It can also be used to rename files or directories.
Syntax: mv [options] source target
If you wanted to rename vvs.txt to vsv.txt, you should give the command as:
mv vvs.txt vsv.txt
After executing this command, vvs.txt would no longer exist, but a file with name
vsv.txt would now exist with the same contents.
12)rm
rmremoves or deletes files from a directory.
Syntax: rm [options] files
In order to remove a file, you must have write permission to the directory where the
will come up asking you whether or not you wish to override the write protection.
The -r option is very handy and very dangerous. -r can be used to remove a directory
and all its contents. If you use the -i option, you can possibly catch some disastrous
13)rmdir
rmdirallows you to remove or delete directories but not their contents. A directory
must be empty in order to remove it using this command.
Syntax: rmdir [options] directories
If you wish to remove a directory and all its contents, you should use rm -r.
For the commands MKDIR and RMDIR the output will be like this:
Testing the Solution:
All the commands will display the output based on it and the options given to
that
command.
If we are giving a command and the option to that command then that option
must be
of that command only otherwise will display the error.
Conclusions :
Using this we can run different command and see the output.
Lab 2
1. Aim: Commands related to inode, I/O redirection and piping, mail, xargs, export, set-unset,
source, ps, kill, jobs.
2. Software Used: Operating System: Linux
3. Source Code/experiment description:
mail:
Send or read e-mail messages.
This stripped-down command-line mail client works fine as a command embedded in a script.
inode:
Piping:
I/O Redirection:
set
The set command changes the value of internal script variables/options. One use for this is to
toggle option flags
which help determine the behavior of the script. Another application for it is to reset the
positional parameters that a script sees as the result of a command (set `command`). The script
can then parse the fields of the command output.
unset
The unset command deletes a shell variable, effectively setting it to null. Note that this command
does not affect positional parameters.
bash$ unset PATH
bash$ echo $PATH
bash$
Example: "Unsetting" a variable
#!/bin/bash
# unset.sh: Unsetting a variable.
variable=hello # Initialized.
echo "variable = $variable"
unset variable # Unset.
# In this particular context,
#+ same effect as: variable=
echo "(unset) variable = $variable" # $variable is null.
if [ -z "$variable" ] # Try a string-length test.
then
echo "\$variable has zero length."
fi
exit 0
export:
The export command makes available variables to all child processes of the running script or
shell. One important use of the export command is in startup files, to initialize and make
accessible environmental variables to subsequent user processes.
Note: Unfortunately, there is no way to export variables back to the parent process, to the process
that called or invoked the script or shell.
Example: Using export to pass a variable to an embedded awk script
#!/bin/bash
# Yet another version of the "column totaler" script (col-totaler.sh)
#+ that adds up a specified column (of numbers) in the target file.
# This uses the environment to pass a script variable to 'awk' . . .
#+ and places the awk script in a variable.
ARGS=2
E_WRONGARGS=85
if [ $# -ne "$ARGS" ] # Check for proper number of command-line args.
then
echo "Usage: `basename $0` filename column-number"
exit $E_WRONGARGS
fi
filename=$1
column_number=$2
#===== Same as original script, up to this point =====#
exportcolumn_number
# Export column number to environment, so it's available for retrieval.
# -----------------------------------------------
awkscript='{ total += $ENVIRON["column_number"] }
END { print total }'
# Yes, a variable can hold an awk script.
# -----------------------------------------------
# Now, run the awk script.
awk "$awkscript" "$filename"
# Thanks, Stephane Chazelas.
exit 0
It is possible to initialize and export variables in the same operation, as in export var1=xxx.
ps:
Process Statistics: lists currently executing processes by owner and PID (process ID). This is
usually invoked with ax or aux options, and may be piped to grep or sed to search for a specific
process.
Example:
bash$ ps ax | grep sendmail
295 ? S 0:00 sendmail: accepting connections on port 25
To display system processes in graphical "tree" format: psafjx or ps ax --forest.
kill:
Forcibly terminate a process by sending it an appropriate terminate signal.
Jobs:
Lists the jobs running in the background, giving the job number. Not as useful as ps.
It is all too easy to confuse jobs and processes. Certain builtins, such as kill, disown, and wait
accept either a job number or a process number as an argument. The fg, bg and jobs commands
accept only a job number.
Example:
bash$ sleep 100 &
[1] 1384
bash $ jobs
[1]+ Running sleep 100 &
"1" is the job number (jobs are maintained by the current shell). "1384" is the PID or process ID
number (processes are maintained by the system). To kill this job/process, either a kill %1 or a
kill 1384 works.
4. Conclusion: In this experiment student learn various commands for shell scripting.
Lab 3
3. SOURCE CODE:
if [ $# -ne 1 ]
then
echo "Usage - $0 file-name" exit 1 fi
if [ -f $1
then
echo "$1 file exist"
else
echo "Sorry, $1 file does not exist"
fi
Logical operators-
integer comparison
-eq
is equal to
if [ "$a" -eq "$b" ]
-ne
is not equal to
if [ "$a" -ne "$b" ]
-gt
is greater than
if ["$a" -gt "$b" ]
-ge
is greater than or equal to
if [ "$a" -ge "$b" ]
-lt
is less than
if [ "$a" -lt "$b" ]
-le
is less than or equal to
if [ "$a" -le "$b" ]
<
is less than (within double parentheses)
(("$a" < "$b"))
<=
is less than or equal to (within double parentheses)
(("$a" <= "$b"))
>
is greater than (within double parentheses)
(("$a" > "$b"))
>=
is greater than or equal to (within double parentheses)
(("$a" >= "$b"))
string comparison
=
is equal to
if [ "$a" = "$b" ]
==
is equal to
if [ "$a" == "$b" ]
This is a synonym for =.
1 [[ $a == z* ]] # true if $a starts with an "z" (pattern matching)
2 [[ $a == "z*" ]] # true if $a is equal to z*
3
4 [ $a == z* ] # file globing and word splitting take place
5 [ "$a" == "z*" ] # true if $a is equal to z*
6
7 # Thanks, S.C.
!=
is not equal to
if [ "$a" != "$b" ]
This operator uses pattern matching within a construct.
<
is less than, in ASCII alphabetical order
if [[ "$a" < "$b" ]]
if [ "$a" \< "$b" ]
Note that the "<" needs to be escaped within a [ ] construct.
>
is greater than, in ASCII alphabetical order
if [[ "$a" > "$b" ]]
if [ "$a" \> "$b" ]
Note that the ">" needs to be escaped within a [ ] construct.
See Example 26-6 for an application of this comparison operator.
-z
string is "null", that is, has zero length
-n
string is not "null".
Else + if equals elif, case structure
elif
clear
echo "Enter first number: "
read a
echo "Enter second number: "
read b
echo "Enter third number: "
read c
if [ $a -gt $b ] && [ $a -gt $c ]
then
echo "$a is greater"
elif [ $b -gt $a ] && [ $b -gt $c ]
then
echo "$b is greater"
elif [ $c -gt $a ] && [ $c -gt $b ]
then
echo "$c is greater"
fi
case structure
if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;; x|
X) let z=$1*$3;; *) echo Warning - $2 invalid operator, only +,-,x,/ operator allowed
exit;;
esac
echo Answer is $z else
echo "Usage - $0 value1 operator value2"
echo " Where, value1 and value2 are numeric values"
echo " operator can be +,-,/,x (For Multiplication)"
fi
While ,for loop
clear
n=1
while [ $n -le 10 ]
do
echo $n
n=`expr $n + 1`
done
clear
for (( i=1; i<=10; i++ ))
do
echo $i
done
Lab 4
1.AIM: Write a shell script to create a file in $USER /class/batch directory. Follow the
Instructions.
Input a page profile to yourself, copy it into other existing file
Start printing file at certain line
Print all the difference between two file, copy the two files at $USER/CSC/2007
directory.
Print lines matching certain word pattern.
2. Software Used:
Operating System: LINUX
3. Source Code :
(i) Input a page profile to yourself, copy it into other existing file;
Solution:-
mkdir p user/class/b1
cd user/class/b1
pwd
read file1
read file2
cp $file1 $file2
cat $file2
mkdir p user/class/b1
cd user/class/b1
pwd
(iii)
read file1
cat > $file1
tail +5 $file1
(iii) Print all the difference between two file, copy the two files at
$USER/CSC/2007 directory.
Solution:-
read file1
read file2
read file3
cat> $ file1
cat> $ file2
read file1
cat> $file1
read f
grep ni $f $file1
Lab 5
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
who |wc l
2. SOTWARE USED:
Operating System: Linux
3. SOURCE CODE:
readfname
cat>fname
ls l $fname
vi $ fname
ls ult $fname
ls clt $ fname
Lab 7
1.AIM:. Write a shell script to print file names in directory showing date of creation & serial no.
of file.
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
who
Output
Show only name and time
root 12:48
show sort by time
12:48 root
Lab 8
1. AIM: Write a shell script to count lines, words & characters in its input. (do not use wc)
2. SOTWARE USED:
Operating System: Linux
3. SOURCE CODE:
read
fname
cat> $ fname
clear
cat $fname
\ \
Output
Create and enter file name
Display all records
11
22
33
Lab 9
1. AIM: Write a shell script to print end of a Glossary file in reverse order using array.
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE
file_name="$1"
if [ "$#" -eq 0 ]
then
echo "Syntax: $0 filename"
exit
elif [ ! -f "$file_name" ]
then
echo "File \""$file_name"\" does not exist"
exit
fi
IFS=$'\n'
declare -a arr
#Read from file_name and store each line into next array location.
while read -r line
do
arr+=("${line}");
done< "$file_name"
#If last line is not \n terminated read returns false, body of while
# is not executed. Instead of saving it in the array directly print it
# because it will be the first line in the file. Also make sure not to
# terminate the line with newline character, so use echo -n
if [ ! -z "$line" ]
then
echo -n "$line"
fi
#Print the lines in reverse order with a newline after each line
# (no -n after echo ensures it. Include the -E parameter to make sure
# no slash '\' are interpreted as escape sequences
while [ $i -ge 0 ]
do
echo -E "${arr[$i]}"
i=$((i-1))
done
Lab 10
1. AIM: Write a shell script to check whether Ram logged in, continue checking further after
every 30 seconds till success.
2. SOTWARE USED:
Operating System: Linux
3. SOURCE CODE:
Invalidoptions()
{
echo "Usage: `basename $0` [OPTIONS]"
echo "OPTIONS:"
echo -e "\t -d for display today's date"
echo -e "\t -u for Logged in users list"
echo -e "\t -f ARG for Disk and Memory Statistics"
echo -e "\t (ARG=D for disk statistics; ARG=M for memory statistics)"
echo -e "\t -c ARG for Top CPU consuming process"
echo -e "\t (ARG=10 means top 10 process)"
echo -e "\t -m ARG for Top Memory consuming process"
echo -e "\t (ARG=10 means top 10 process)"
echo -e "\t Note: Only one option at a time and -f,-c and -m require argument"
exit 1
}
Isnumber()
{
if [ $1 -eq $1 2> /dev/null ]
then
:
else
echo -e "You supplied bad argument, \"$1\" is not a number"
Invalidoptions
fi
}
if [ $# -lt 1 -o $# -gt 2 ]
then
Invalidoptions
if [ $# -eq 1 -a "$1" != "-d" -a "$1" != "-u" -a "$1" != "-f" -a "$1" != "-c" ]
fi
then
Invalidoptions
fi
choice=
top="head -$2"
while getoptsudf:c:m: choice
do
case $choice in
d) echo -e " Today's Date: \c"
date +" %d-%h-%Y Time: %T";;
u) echo -e "\tCurrently Logged In Users"
who;;
f)
if [ "$OPTARG" = "D" ]
then
echo -e "\t\tDisk Statistics"
df -h | grep "%"
elif [ "$OPTARG" = "M" ]
then
echo -e "\t Memory Statistics "
free -m | awk 'BEGIN{printf "\t\tTotal\tUsed\tFree\n"; OFS="\t" }\
/Mem/||/Swap/{printf "\t"; print $1,$2,$3,$4}'
else
Invalidoptions
fi;;
m) Isnumber $OPTARG
k3sort="sort -nr -k 3"
echo -e " PID PPID MEM CPU COMMAND "
ps -Aopid= -o ppid= -o pmem= -o pcpu= -o comm=|$k3sort|$top;;
c) Isnumber $OPTARG
k4sort="sort -nr -k 4"
echo -e " PID PPID MEM CPU COMMAND "
ps -Aopid= -o ppid= -o pmem= -o pcpu= -o comm=|$k4sort|$top;;
esac
done
Output:
[root@localhost blog]# sh sys_monitor2.sh -u
Currently Logged In Users
root tty7 2009-09-23 13:48 (:0)
root pts/2 2009-09-23 14:36 (:0.0)
2. SOTWARE USED:
Operating System: Linux
3. SOURCE CODE:
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
i=2
rem=1
echo "Enter a number"
read num
if [ $num -lt 2 ]
then
echo -e "$num is not prime\n"
exit 0
fi
while [ $i -le `expr $num / 2` -a $rem -ne 0 ]
do
rem=`expr $num % $i`
i=`expr $i + 1`
done
if [ $rem -ne 0 ]
then
echo -e "$num is prime\n"
else
echo -e "$num is not prime\n"
fi
BEYOND CURRICULUM
EXPERIMENT NO. 1
2. SOURCE CODE:
E_BADARGS=65
if [ ! -r "$1" ] # Need at least one
then #+ valid file argument.
echo "Usage: $0 files-to-process"
exit $E_BADARGS
fi
cat $* #| Contents of specified files to stdout.
2. SOURCE CODE:
clear
i="y"
echo "Enter name of database "
read db
while [ $i = "y" ]
do
clear
echo "1.View the Data Base "
echo "2.View Specific Records "
echo "3.Add Records "
echo "4.Delete Records "
echo "5.Exit "
echo "Enter your choice "
readch
case $ch in
1)cat $db;;
2)echo "Enter id "
read id
grep -i "$id" $db;;
3)echo "Enter new std id "
ireadtid
echo "Enter new name:"
readtnm
echo "Enter designation "
read des
echo "Enter college name"
read college
echo "$tid $tnm $des $college">>$db;;
4)echo "Enter Id"
read id
# set -a
# sed '/$id/d' $db>dbs1
grep -v "$id" $db>dbs1
echo "Record is deleted"
cat dbs1;;
5)exit;;
*)echo "Invalid choice ";;
esac
echo "Do u want to continue ?"
read i
if [ $i != "y" ]
then
exit
Fi
done