Kajal. Linux
Kajal. Linux
COLLEGE BHARATPUR
IV -SEMESTER
COMPUTERSCIENCE&ENGINEERING
Assignments:
1. Shell script to display “Hello World!”
2. Script that takes two no. as input from user and perform addition,
Subtraction, Multiplication and Division.
3. Script to store five different names in an array and print each name in new
4. line
5. Script to generate system report that include disc usage and C.P.U usage
6. Script to send an e-mail notification when specific event occurs.
Script to automate the deployment of a web application
Lab 1
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 cat allows 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/
Ahandy 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).
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 vvsdirectory contained the word “mca” you could use grep
to search the directory and match those files with that word. All that you have to do
is give the command as shown:
grep „mca‟/vvs/*
The * used in this example is called a meta-character, and it represents matching zero
or more of the preceding characters. In this example, it is used to mean “all files and
directories in this directory”. So, grep will search all the files and directories in
vvsand tell you which files contain “mca”.
10)ls
Is will 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). | more can 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
rm removes 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 will ask you to confirm whether you really want to remove a file
before going ahead and doing it.
13)rmdir
rmdir allows 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:
Conclusions :
Using this we can this we can run different command and see 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.
Piping:
Example: Piping the output of echo to a read
#!/bin/bash
#
badread.sh:
# Attempting to use 'echo and 'read'
#+ to assign variables non-interactively.
a=aaa
b=bbb
c=ccc echo
"one two
three" |
read a b c
# Try to reassign a, b, and c.
echo
echo "a = $a" # a = aaa
echo "b = $b" # b =
bbb echo "c = $c" # c =
ccc
# Reassignment failed.
#
# Try the following alternative. var=`echo
"one two three"`
set -- $var a=$1;
b=$2; c=$3 echo
"------ "
echo "a = $a" # a = one
echo "b = $b" # b = two
echo "c = $c" # c = three
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
thepositional 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: Unsettinga
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
makeaccessible 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:
Logical operatorsinteger
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, inASCII alphabetical order
if [[ "$a" > "$b" ]] if [ "$a" \> "$b" ]
Note that the ">" needs to be escaped within a [ ] construct.
See Example26-6for 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
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. SourceCode :
(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
(ii) Start printing file at certain line
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
(iii) echo “Enter a file name” read
file1
echo “Enter contains in
$file1” cat > $file1 echo “Start
Printing at 5 line “ tail +5
$file1
(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. SOURCECODE:
2. SOTWAREUSED:
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 “
Lab 6
ls –l $fname echo “
Modification $fname” vi $
fname echo “ show access
time “
ls –ult $fname
echo “ show modification time “ 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:
Output
Showonly name and time
root 12:48
showsort bytime
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. SOURCECODE:
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. SOURCECODE
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. SOTWAREUSED:
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
esac
done
Output:
[root@localhost blog]# sh sys_monitor2.sh -u
In Users
root Currentlytty7 Logged2009 -09 -23
13:48 (:0)
root pts/2 2009-09-23 14:36 (:0.0)
[root@localhost blog]# sh sys_monitor2.sh -d
Todays Date: 23-Sep-2009 Time: 16:50:38
[root@localhost blog]# sh sys_monitor2.sh -m 5
PID PPID MEM CPU COMMAND
3122 3102 9.6 3.0 firefox
2765 2540 1.9 0.0 nautilus 3849
1 1.7 1.0 ktorrent
2882 1 1.6 0.0 tomboy
2810 1 1.6 0.0 /usr/bin/sealer
Lab-11
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
BEYONDCURRICULUM
Lab 13
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.
Lab 14
1.Shell script to perform database operations for student data like view, add and delete records
in Unix / Linux.
3.SOURCE CODE:
#!/bin/bash
echo “hello world!”
OUTPUT:
Assignment no.2
1. AIM: Write a script that takes two numbers as input from the user and performs
addition, subtraction, multiplication, and division..
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
#!/bin/bash
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
# Function to display disk usage display_disk_usage()
{
echo "Disk Usage:"
df -h echo
}
# Function to display memory usage
display_memory_usage() {
echo "Memory
Usage:" free -h echo
}
# Function to display CPU usage display_cpu_usage()
{
echo "CPU Usage:" top
-bn1 | grep "Cpu(s)"
echo
}
# Generate the system report
echo "System Report"
echo " "
display_disk_usage
display_memory_usage
display_cpu_usage
OUTPUT:
Assignment no.5
1. AIM:Write a script to end an email notification when a specific event occurs (e.g., disk
usage exceeds 90%).
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
# Set the threshold for disk usage
THRESHOLD=90
# Define the recipient email address
EMAIL="[email protected]"
# Function to check disk usage and send an email if the threshold is exceeded
check_disk_usage() {
# Get the disk usage percentage for the root partition
USAGE=$(df / | grep / | awk '{ print $5 }' | sed
's/%//g') # Check if the usage exceeds the threshold if
[ $USAGE -gt $THRESHOLD ]; then
SUBJECT="Disk UsageAlert: $(hostname)"
MESSAGE="Disk usage on $(hostname) has exceeded the threshold of
$THRESHOLD%. Current usage is ${USAGE}%."
# Send the email notification
echo $MESSAGE | mail -s "$SUBJECT" $EMAIL fi
}
# Run the disk usage check
check_disk_usa
Assignment no.6
1. AIM:Develop a script to automate the deployment of a web application (e.g., pulling
code from a repository, installing dependencies, starting the server).
2. SOFTWARE USED:
Operating System: Linux
3. SOURCE CODE:
# Set variables
REPO_URL="https://github.com/yourusername/yourrepository.git"
APP_DIR="/path/to/your/app"
BRANCH="main"
PM2_APP_NAME="your-app-name"
# Function to pull the latest code from the repository
pull_code() {
echo "Pulling latest code from repository..."
if [ ! -d "$APP_DIR" ]; then
git clone $REPO_URL$APP_DIR
else
cd $APP_DIR git pull
origin $BRANCH
fi
}
# Function to install dependencies
install_dependencies() {
echo "Installing
dependencies..." cd $APP_DIR
npm install
}
# Function to start the server using pm2
start_server() { echo "Startingthe server..." cd
$APP_DIR pm2 start npm --name
$PM2_APP_NAME -- start
}
# Function to stop the server using pm2
stop_server() {
echo "Stopping the server..."
pm2 stop $PM2_APP_NAME
}
# Function to restart the server using pm2
restart_server() {
echo "Restarting the server..."
pm2 restart $PM2_APP_NAME
}
# Function to deploy the application
deploy() {
stop_server
pull_code
install_dependencies
start_server
}
# Execute the deployment
deploy
Output: