4CS4-24 LINUX Lab (2) (2)
4CS4-24 LINUX Lab (2) (2)
Technology
Lab Manual
Linux Shell Programming Lab
(4CS4-24)
How to write Source program in practical file:
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 –d “2 days ago”
[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) stands for “change directory”. This command is the key command to
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 specified directory, so you won’t have to copy one file at a
time.
9) grep
The grep command searches a file or files for lines that match a provided regular
expression (“grep” comes from a command meaning to globally search for a regular
expression and then print the found matches).
10) ls
lswill list all the files in the current directory. If one or more files are given, ls will
display the files contained within “name” or list all the files with the same name as
“name”. The files can be displayed in a variety of formats using various options.
Syntax: ls [options] [names]
lsis a command you'll end up using all the time. It simply stands for list. If you are in
a directory and you want to know what files and directories are inside that directory,
type ls. Sometimes the list of files is very long and it flies past your screen so quickly
you miss the file you want. To overcome this problem give the command as shown
below:
ls | more
The character | (called pipe) is typed by using shift and the \ key. | more will show as
many files as will fit on your screen, and then display a highlighted “more” at the
bottom. If you want to see the next screen, hit enter (for moving one line at a time) or
the spacebar (to move a screen at a time). | morecan be used anytime you wish to
view the output of a command in this way.
A useful option to use with ls command is -l. This will list the files and directories in
a long format. This means it will display the permissions (see chmod), owners,
group, size, date and time the file was last modified, and the filename.
drwxrwxr-xvvs staff 512 Apr 5 09:34 sridhar.txt
-rwx-rw-r-- vvs staff 4233 Apr 1 10:20 resume.txt
-rwx-r--r-- vvs staff 4122 Apr 1 12:01 favourites.html
There are several other options that can be used to modify the ls command, and many
of these options can be combined. -a will list all files in a directory, including those
files normally hidden. -F will flag filenames by putting / on directories, @ on
symbolic links, and * on executable files.
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
file is located. While removing a which does’t have write permission on, a prompt
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
mistakes because it’ll ask you to confirm whether you really want to remove a file
before going ahead and doing it.
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.
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.
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.
source, . (dot command):
This command, when invoked from the command-line, executes a script. Within a script, a
source file-name loads the file file-name. Sourcing a file (dot-command) imports code into the
script,
appending to the script (same effect as the #include directive in a C program). The net result is the
same as if the "sourced" lines of code were physically present in the body of the script. This is
useful in situations when multiple scripts use a common data file or function library.
Example: "Including" a data file
#!/bin/bash
. data-file # Load a data file.
# Same effect as "source data-file", but more portable.
# The file "data-file" must be present in current working directory, #+
since it is referred to by its 'basename'.
# Now, reference some data from that file.
echo "variable1 (from data-file) = $variable1"
Advanced Bash-Scripting Guide
Chapter 15. Internal Commands and Builtins 198
echo "variable3 (from data-file) = $variable3"
let "sum = $variable2 + $variable4"
echo "Sum of variable2 + variable4 (from data-file) =
$sum" echo "message1 (from data-file) is \"$message1\""
# Note: escaped quotes
Print_messageThis is the message-print function in the data-file.
exit 0
File data-file for above Example Must be present in same directory.
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.
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 =.
!=
is not equal1 [[
to $a == z* ]] # true if $a starts with an "z" (pattern
if [ "$a" != "$b" ] 2 [[ $a == "z*" ]] # true if $a is equal to z*
matching)
3 uses pattern matching within a construct.
This operator
< 4 [ $a == z* ] # file globing and word splitting take
place
is less than, 5 [ "$a"
in ASCII == "z*" ] #order
alphabetical true if $a is equal to z*
6
if [[ "$a" < "$b" ]]
if [ "$a" \<7"$b"
# Thanks,
] S.C.
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
-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
Loop clear
n=1
while [ $n -le 10 ]
do
echo $n n=`expr
$n + 1` done
Loop clear
for (( i=1; i<=10; i++ ))
do
echo $i
done
2. Software Used:
Operating System: LINUX
3. Source Code :
(i) Input a page profile to yourself, copy it into other existing file;
Solution:-
echo”create a file in /user/class/batch in
directory” mkdir –p user/class/b1
echo “Display present working DIR”
cd user/class/b1
pwd
echo “Enter a file name”
read file1
echo “Enter contains in $file1”
cat > $file1
echo “Enter existing file
name” read file2
echo “Display copy of contains $file1 to
$file2” cp $file1 $file2
cat $file2
(iii) Print all the difference between two file, copy the two files at
$USER/CSC/2007 directory.
Solution:-
echo “enter first file
name” read file1
echo “enter second file
name” read file2
echo “enter third file name”
read file3
echo “Enter contains to
$file1” cat> $ file1
echo “Enter contains to
$file2” cat> $ file2
echo “Display difference between $file1 and $file2 copy to $file3” diff
–a $file1 $file2 >
$file3 cat $file3
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
Viva-Voce questions
1. Which option of the kill command sends the given signal name to the specified process?
2. Which command removes a directory from directory stack?
3. The ‘logout’ built in command is used to
Lab-6
1. AIM: Write a shell script to change data format. Show the time taken in execution of this
script.
2. SOTWARE USED:
Operating System: Linux
3. SOURCE CODE:
echo “ Enter file name “
readfname
echo “ Input contains in
$fname” cat>fname
echo “Display create file than current time
“ ls –l $fname
echo “ Modification $fname”
vi $ fname
echo “ show access time “
ls –ult $fname
echo “ show modification time “
ls –clt $ fname
Viva-Voce Questions
1. Which command prints the accumulated user and system times for processes run from the shell?
2. Which command is used to identify file type?
Lab7
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:
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 –p “create file name “
fname
echo “input the contains of file “
cat> $ fname
clear
echo “ Display all record “
cat $fname
echo “ show file line , word ,char”
gawk ‘{ nc+=length ($0)+1nw +=NF}
END ‘{print “ line =” NF , “\n word =”nw, “\n char =”nc}’ $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)
1. AIM: Write a shell script to compute GCD & LCM of two numbers.
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