Linux
Linux
It is software program designed to act as interface between a user and the computer. It control s the hardware, manages system resources and supervises interaction between the system and its users. Functions of an operating system Command interpretation Interprets the command typed in by the user and translates it to the machine lan guage. Also translates the result to user understandable form. Peripheral management The OS manages the task of accepting input from keyboard and other devices, send ing the output to the printer, screen or other devices. Memory management Many processes will be running in a computer. How much memory is to be allotted to each process is decided by the OS. Process Management The amount of time to be given to each process is decided by the OS. Types of operating systems Single user Multi-user Network
Features of LINUX Kernel programming interface Kernel is the heart of the operating system, responsible for controlling the res ources and scheduling user jobs in such a manner that each user gets equal share of system resources. All programs interact with the kernel through the system c alls. Multi-user Many users can access the system resources. System resources are utilized to the maximum and cost per user is minimized. One user on a machine cannot user all d evices attached to the system. Multitasking It allows a user to run more than one job at a time. The processes can communica te with each other and are protected from one another. File system
File system arranges the files in different directories. Other new features X windows gives GUI features
Accessing remote system for mail, programs can be run on one machine and res ults can be displayed on another etc. LINUX includes compilers and interpreters for many languages like, Pascal, l isp, fortran, ada, c, cobol Screen oriented editors Email programs
Parts of LINUX Kernel Kernel forms the core of LINUX. This interacts with the hardware. It is loaded i nto memory when the system is loaded. its functions are Managing system resources Allocating time for different users and processes Deciding process priorities and performing them
Kernel doesn t interact with user directly. But it starts up a separate file calle d shell. Shell Shell interacts with the user and computer. Its features are: Interactive processing Background processing Input /output redirection
Pipes: simple programs can be developed to do complex operations with minimu m effort using pipes. Wild card patterns Shell scripts Shell variables Programming language constructs
Tools and applications LINUX supports applications such as word processors, spreadsheets, databases etc . usage of simple commands
$date //gives you the system date $who shows you the details of users logged in to linux $ who am i gives you the curent user $ man who gives the help on who, you can get help on any command with man folloed by the p articular command $pwd present working directory with path /user/temp $ls gives the list of files $ls -l files in the long format drwxr--r--r 2 anu student 34 jan 10 199 9 12:24 abc.c the first char d stands for filetype directory file, the other type is ordinary file the next three chars rwx is read, write, execute permission for owner next three the same for group, next three the same for others rest of the result indicates the following no of links owner of the file group file size file creation date and time name of the file $mkdir temp makes a directory $cd jack chages to directory jack
$rmdir temp removes the directory temp //usage of file commands $ cat > mat create a file called mat after typing some thing press ctrl +d to finish $cat mat displays the contents of the file $head -4 wordlist will display the first four lines of the file $tail +10 mall displays from the 10th onwards $tail -4 mall displays the last 4 lines $cp temp temp2 copy temp to temp2 $in temp sametemp makes a additional name for the same file , it is not a copy an alias name $ mv temp tempnew renames the file or moves the files or directory $rm -i temp asks the user before deleting the file $rm -r temp deletes the entire file and directory $ rm -i -r temp after asking delete one by one Chapter 2 A file is just a sequence of bytes, which may contain text, binary data, or even machine language instructions in LINUX all information is treated as files. Dir ectory and devices are also treated as files. Standard input, output, error devi ces are treated as files files are stored in hierarchical order and grouped together
When a file system starts, first the file /boot is read and then /Linux is read /bin directory contains the executables of Linux commands written in c or shell scripts /etc directory contains other additional commands that are related to the system maintenance and administration. it contains several files with information abou t users, terminals and devices /lib library functions that can be used by the programmers /dev stores files related to devices /usr a directory is created for each user to have a private work area. It is cal led users home directory Standard input and output is keyboard, terminal screen they are numbered as 0 an d 1. standard error is terminal screen numbered as 3 output and input can be given to any other device using redirection $date >today it creates a file called today with the output of the date command $cat <names it will direct the contents of the file names to cat command. $ cat<name>list this copies the content of the files names to a new file list $ ls ch* all files starting ch $ls ch?.? ? represents one character while * many $ ls ex[1-3] will list range of files ex1,ex2, ex3 //variables $ echo ${HOME} gives you your home directory Other environment variables are PS1 (where $ prompt is stored, by changing the p rompt will change) ,PATH, TERM (the terminal type),HOMR, LOGNAME,MAIL(path name of messages),PS2 (the Bourne shell prompt defalut >) . profile file contains login name, home directory name etc and will be executed if it resides in the home directory. //more file commands
$read var1 used in shell scripts to take a user input to a variable $echo "how are you" $date +%r the formatted output of date +%D +%H +%M +%S +%T +%w +%a +%h +%r +%y $wc temp 2 14 69 temp the no of lines, words, and characters $ wc lwc temp HH:MM:SS day of the week abbr.weekday abbr. month time in AM/PM last two digits of the year mm/dd/yy HR 00 to 23
l for line, w for words and c for characters $wc l temp only line count $find . -print find the path of all our files in directories $ find games/play -type f -name "P*" -mtime +5 -exec rm {} \; type f for files d for directory name for wild card mtime +5 modified 5 days before current date. if -5 modified during last 5 days exec execute command in this case rm (delete all selected) {}\; should always gi ves with exec command.
-ok instead of exec will prompt //changing file permissions $chmod -x air.c revoke execution permission 1 for read, 2 for write, 4 for execute. first digit for user, next for group, an d last for others all permission is 1+2+4 =7 for each category $chmode 777 text Granting all permissions to all three Chapter 4 Pipes and filters It is possible to perform multiple tasks in one command. Redirection is one wa y to do this. But it creates lot of temporary files that are redundant and occup y disk space. Pipes and filters are used to overcome this problem. $ who 16 The output of who is given to word count with c option. Pipes make temp files only in memory $ cat text head 3 wc c
Filters Filters are used to extract the lines, which contain a specific pattern , to arr ange the contents of a file in a sorted order, to replace the existing character s with other characters, etc. Filters are also used to store the intermediate results of a long pipe. We can e xtract specific columns of a file and can merge two or more files together using filters. The sort filter The options of the sort command are $sort The input is accepted from key board and the result is sorted. $ sort r reverse alphabetical order $ sort f r, -f, -n, -b, -t
according to numeric value $ sort +1 2 names sorts according to middle name if fist, middle , last names are given in the fil e separated by a space or tab. This is called +pos1, -pos2 $ sort +2 3 names to sort according to last name if the field separator is some other character $ sort t : $sort u emp removes the duplicate records $ sort o newnames names +2 3 names t option is used
removes black spaces in front to the names Combinations -rn, -nr -uf, -fu +4n 5
+3nr 2, +3rn 2 the grep filter grep is used to search a pattern $ grep asia data data
$ grep i asia
-v lines that do not match -c displays the count of lines that match -n display matched lines with line number -i ignore case $ grep new[a-c] names
$grep e$
names
lines ending e egrep extended global search for regular expression $ egrep India Nigeria argentina data
line containing any of the three contents of data India 6890 asia Nigeria 3212 africa Argentina 1234 south America Contens of countries Nigeria India $ egrep f countries data India 6890 asia Nigeria 3212 africa Takes data from both the files and joins $ egrep ica$ data gives all lines ending ica $fgrep this is data
to match a fixed string without any pattern -x is used for exact match the uniq filter $uniq mast removes all duplicates options -d displays only lines which are duplicated -u displays only lines with single occurrences -c displays the no of times each line is occurred preceding the line The more
$ who
more
-d for specifying the delimiter -f2 only the second field of the file $ cat mast cut =d : f3
using pipe in addition to cut paste if we have 3 files one with first name, one with middle name, one with last name $ paste firstname secondname lastname joins them in the order tee Using pipes we may get undesired result or error message. To debug an intermedia te file can be used to store the intermediate data $cat mast tr this command maps the characters to alternate characters $ cat bag tr [a-z] [A-Z] sort tee temp cut d : f1
Converts to upper case -s removes multiple spaces to single space $ls l grep ^d
filter for directory names Display the first field of the first ten lines $cat text sort head cut d f1
Editors chaper 5 Vi,ex, ed, sed, emacs Vi and ex editors have the same commands one is a screen editor and other is lin e editor Vi edits a file in memory and replaces the original file only when we quit
$ vi filename $ vi +3 filename opens the file and places cursor on the third line keys enter: goes to the next line in command mode, in esc mode executes the command, inserts a new line in insert mode Esc: goes to command mode /: helps to search for a string following / ?: same as / : takes you to esc mode :s/X/Y/g search and replace string X with Y from the cursor
:g/X/s/Y/g same as above for entire file movement of cusor press esc key to enter command mode h or backspace l or space bar k or j or + w W e E b B ^ $ L G Ctrl F Ctrl B Ctrl D left right up down forward by one word forward by one word punctuations ignored to last character of the word same ignoring punctuations moves backward by word now you know to the beginning of line end of line last line of the file 2G go to second line forward one screen backward one screen forward half screen
Press i to be insert mode O o a A inserts line above the present line below line append text after the cursor append text at end of line
Deleting data in vi dd dw dW x X D u j line numbers : set number :set nonumber : set showmode :2co5 :1,3co7 :2mo5 :5,7 d : . +4d : .-5d :q! :wq move delete 5 to 7 delete 4th line from present position delete 5th line above the present line quit without saving save and quit copy second line below 5th line copy first three lines below 7th line deletes line deletes word delete word including punctation deletes char deletes char before cursor deletes to line end undo place cursor at end of line and press j to join the next line
:x ZZ
old copy with new and quit make chages and quits from the command mode
Chapter 6 shell programming A set of commands to be performed can be entered into a file by using any of the editors 6.1 program to get users name and greeet $cat>greet echo please enter your name:
//to execute give $sh greet //or change the x permission and $ chmod u+x greet $ greet //create a variable pet, assign a value and display $ pet=rabit $echo $pet //environment variables such as PATH,PSI,HOME //all variables defined by user are local variable //comment lines # is used for comment lines //escape char is \ //it is used before characters which got a special meaning for LINUX // example \* // backquotes are used for command substitution $echo `date` //the output of date command will be echoed // exit command to exit with 0 or 1, 0 is successful //comparison eq, -ne, -gt, -lt, -ge, -le
//logical operators !,-a,-o for not, and, or // && is used when a command is to be executed if the other command is successfu l $grep good gems&& echo pattern found
//echo is executed only if the word good is found in file gems $grep good gems echo pattern not found
//echo is executed if the word is not found Programming constructs if ..then ..elif..then ..else.. fi for..do..done while..do..done until..do..done case esac if construct if (grep read text>/dev/null) then echo Pattern found else echo fi pattern not found
elif (grep read passage>/dev/null) then echo else echo fi //case pattern not found Pattern found in passage
menu 1. your current directory 2. todays date 3. list is users logged in your choice
*) echo esac
//* will executed if the user fails to enter a valid command //for for k in 1 2 3 4 5 do echo the number is $k echo done //while while grep Lynda names >/dev/null do echo exit done //until until ls do echo exit file not found grep red >/dev/null pattern found the square of the nuber is `expr $k \* $k
done echo //test $pet=dog $test $pet=dog $echo $? // test compares //$? Returns the exit status of the last executed command $cat op echo what is the best operating system? file red found here
read ans if test $sans=LINUX then echo else echo fi // instead of test command [] can be used echo enter employee\`s basic: never heard of $ans very good
read basic if [$basic then HRA= expr $basic/5 echo $HRA elif [$basic ge 4000 a $basic le 5000] gt 5000]
HRA= expr $basic/ 4 echo $hra else HRA= expr $basic /10 echo $HRA
fi //to display menu to perform appropriate action echo echo echo echo echo menu 1.Display long listing of files 2. Displays long listing of files including hidden files 3. delete files from the directory enter your choice
read choice case $choice in 1) 2) 3) ls l;; ls al;; echo enter file to be deleted
read file rm $file echo $file deleted ;; *) echo invalid choice ;; esac Chapter 7 sell programming II Two commands can be executed if they are separated by semicolon. $date;who wc l >temp
The file temp will contain only the word count of who, the date will be displaye d on the screen. $(date;who wc l) >temp
Putting brackets will take all output to file temp Test on characters Test whether a string is null add z to test command or n zero $echo enter your name: read name if [-z then $name ] n to check whether it is no
hello $name
Test on file types -f -d -r -w -x -s checks for existence and whether it is an ordinary file. checks for existence and whether it is a directory. checks for existence and is readable checks for existence and is writable checks for existence and is executable checks for existence and is not empty
$# $* $0
the number of the positional parameters list of positional parameters the name of the command being executed
#check for the existence of the file and check if it is executable # usage $0 filename if [$# -lt 1] then echo exit fi if [ -x $1] then echo else echo fi $1 does not have execute permission $1 has executable permission invalid usage
#ex 7.5 #to illustrate the usage of test command s options #usage $0 file1 file2 file3 if [$# -lt 1] then echo invalid usage exit fi while [ ! z do if [ -f $1] then echo $1 is an ordinary file elif [-d $1] then echo else echo fi shift done $1 does not exist $1 is a directory $1 ] // while not null the parameter
-x option will display the result of each line. A + sign will be shown in front of the commnds
hello there
Handling strings When strings are used with spaced words enclose them in double quotes. Redirection If entire out put inside while loop is go into a file redirect it to a file aft er done key word Done>$fname Shell functions Functionname () command Or Functionname(){ Commands } $home () { ls l ^d
} //typing home at $ prompt will give list of directories The while loop To terminate a loop press ctrl +d or del key while true do commands done until false loop until false do ps f
sleep 5 echo LINUX is at your service echo done //ps displays the current process information, then waits for 5 seconds and the loop continues till del is pressed. press del to exit
*) num =$1 esac the break and continue statements same as c background process $sort text & 345 $_ the file text is sorted in the background 345 is the PID
$ps
p 345
gives the process information of 345 nohup command when we logout all foreground and background commands are terminated. If you wan t them to be running $ nohup du / & 654 to see if the process is continuing loggin again. The output of the command will be stored in a file called nohup.out $kill 654 will terminate the background command Shprog1 echo Enter the values of a,b,c read a b c scale = 6 echo you have entered echo $a $b $c echo their sum and product is x = `echo $a + $b + $c y = `echo $a\*$b\*$c bc bc l` l`
echo $x $y Shprog2 #THIS PROGRAM DEMONSTRATES THE USE OF if echo enter any number read n if test $n then echo $n is positive else echo $n is negative fi Shprog4 #THIS IS PROGRAM FOR IF ELSE WITHOUT TEST echo enter the basic salary read b scale = 2 if [$b lt 1500] then hra=`echo $b\*10/100 bc l` gt 0
da=`echo $b\*90/100 bc l` else hra=500 da=`echo $b\*98/100 bc l` fi g=`echo $b+$hra+$da bc echo gross salary = $g Shprog5 echo ENTER THE FILE NAME read fname if [ -f $fname] then l`
echo THE FILE EXISTS else echo FILE WITH THIS NAME DOES NOT EXIST fi Shprog6 #PROGRAM FOR STRING COMPARISON echo ENTER THE TWO STRINGS read str1 str2 if [ $str1 = $str2 ] then echo THE STRINGS ARE IDENTICAL else echo STRINGS ARE NOT IDENTICAL fi Shprog7 #Program to check whether file has a permission to write echo Enter the file name read fname if [ -w $fname ] then echo Type text to append. To stop press Ctrl D. cat >> $fname else echo The file has no write permission fi Shprog8 #Program to give grades echo Enter the marks in the five subjects scale=2 read m1 m2 m3 m4 m5 per=`expr $m1 + $m2 + $m3 + $m4 + $m5` per=`expr $per / 5`
echo $per if [ $per lt 35 ] then echo GRADE = FAIL fi if [ $per ge 35 then echo GRADE = THIRD fi if [ $per ge 45 then echo GRADE = SECOND fi if [ $per ge 60 then echo GRADE = FIRST fi Shprog9 #Program to check whether the number is +ve or echo Enter the number read a if [ $a then echo a is negative elif [ $a gt 0 ] then echo a is positive else echo a is neither +ve nor fi Shprog10 ve lt 0 ] ve a $per lt 75 ] a $per lt 60 ] a $per lt 45 ]
#Program to print the day of the week using case in echo Enter the day number read num case $num in 1) 2) 3) 4) 5) 6) 7) echo Sunday;; echo Monday;; echo Tuesday;; echo Wednesday;; echo Thursday;; Friday;; Saturday;;
*) echo Enter the number bet 1 to 7;; esac Shprog11 #Program to find the type of the character entered echo Enter any character read c case $c in [a-z]) echo Small Case letter;; [A-Z]) echo Capital letter;; [0-9]) echo digit;; ?) echo special symbol;; *) echo more than one character, reenter;; esac Shprog12 #Program to find the pattern echo Enter the word read str case $str in [aeiou]*) echo The word begins with a vowel;; [0-9]*) echo The word starts with a digit;; *[0-9]) echo The word ends with a digit;;
????) echo The word entered is 4 lettered word;; *) echo The word entered is either starts with a consonant or incorrect input;; esac Shprog13 #Program to find the type of the file echo Enter the name of the file read fname case $fname in *.c) echo it s a c prog file;; *.out) echo it is an output file;; *) echo not sure;; esac Shprog14 #Menu driven program echo enter echo 1 to see the contents of /etc/passwd echo 2 to see list of users echo 3 to see present working directory echo 4 exit echo enter your choice read n case $n in 1) 2) 3) 4) ls /etc;; ls /home;; pwd;; exit;;
*) echo enter the choice as 1,2,3or4;; esac Shprog15 #Program to print first n numbers and their sum:while loop
i=1 sum=0 while [ $i do echo $i sum=`expr $sum + $i` i=`expr $i + 1` done echo The sum is= $sum echo end of prog15 Shprog16 #Program to call another file echo hello!! echo date is date echo call prog15 bash shprog15 echo end of the prog16 Shprog17 #Program to print first n numbers and their sum:do until i=1 sum=0 until [ $i do echo $i sum=`expr $sum + $i` i=`expr $i + 1` done echo The sum is= $sum Shprog18 #program: for loop sum=0 gt 10 ] le 10 ]
for i in 1 2 3 4 5 6 7 8 9 10 do sum=`expr $sum + $i` echo $i i=`expr $i + 1` done echo The sum is= $sum Shprog19 #Program to display the directories and files echo The directories are echo for file in * do if [ -d $file ] then echo $file fi done echo The files are echo for file in * do if [ -f $file ] then echo $file fi done shprog20 #Command line argument program #Type the string which you want to read after the file name i=1
for word in $* do echo $word i=`expr $i + 1` done echo `expr $i Shprog21 function fun() { echo "Hello How r u?" echo "-------------------" } echo "This is function call demo" fun masti echo "Function call over" Shprog22 function masti() { echo "***************" } Shprog23 ---------------------------------------------------# -----------------------------------------------------------# Program to check given number is perfect or not. 1`
while [ $i -lt $n ] do k=`expr $n % $i` if test $k -eq 0 then sum=`expr $sum + $i` fi i=`expr $i + 1` done if [ $n -eq $sum ] then echo The given number is perfect number else echo The given number is not perfect fi Shprog24 -------------------------------------------# -------------------------------------------------------------# Program to check entered number is prime or not.
# -------------------------------------------------------------clear echo "Enter the number" read num i=2 flag=0 while [ $i -lt $num ] do k=`expr $num % $i` if test $k -eq 0 then flag=1
fi i=`expr $i + 1` done if test $flag -eq 0 then echo "Number is prime" else echo "Number is not prime" fi Shprog25 # ---------------------------------------------------# Program to check number is even or odd.
# ----------------------------------------------------
echo "Enter the number" read no k=`expr $no % 2` if test $k -eq 0 then echo "Number is even" else echo "Number is odd" fi Shprog26 # Program to print even number series.
echo "Enter limit" read limit echo "Even number series" while [ $no -le $limit ] do echo $no
no=`expr $no + 2` done Shprog27 # cls echo "Do U want to execute file ? (Y/N) " read ch while [ $ch = 'y' ] do echo Enter filename to execute :read filename cls cat $filename echo "--------------------------------------------------" echo " " sh $filename sleep 8 cls echo "Do u want to continue ? (Y/N) " read ch done -------------------------------------------------------Shprog28 #Write a shell script for expression evaluation Program for continuation of any file ( for execution )
# ------------------------------------------------fact=1
i=1 echo "Enter the number :" read n while [ $n -ge $i ] do fact=`expr $fact \* $i` i=`expr $i + 1` done echo "Factorial = $fact" Shprog29 # Enter a filename and check
clear echo Enter filename : read file if [ -s $file ] then if [ -f $file ] then echo "--------------------------------------" cat $file echo "--------------------------------------" elif [ -d $file ] then ls -i $file fi else echo "This file is empty" fi -----------------------------------------------Shprog30 # -------------------------------------------------------
# -------------------------------------------------------
clear echo Enter number read n i=1 sum=0 while [ $i -le $n ] do sum=`expr $sum + $i` i=`expr $i + 1` done echo "Summation = $sum"
-------------------------------------------------Shprog31
echo "Print table" j=1 echo Input number read x for i in 1 2 3 4 do j=`expr $x \* $i` echo $j i=`expr $i + 1` done -------------------------------------------------Shprog32 # Write a shell script to find which user login first time.
# x=`who cut -c25-30 sort head -1` name=`who grep $x cut -f1 -d" "` echo The first login person is $name ----------------------------------------------------echo "The value of variable x is $x" x=20 echo "The value of the variable x is $x" ----------------------------------------------------Shprog33
while echo -n "Name : " do read name case "$name" in *[^a-zA-Z]*) echo "Can contain only alphabets and spaces" continue;; " ") echo "Name not entered" continue;; *) echo "$name">>stu break;; esac done Shprog35
for i in fly spinder frog do echo I know an old lady who swallowed a $i. echo Swallowed a $i\? echo Swallowed a $i! done
------------------------------------------------------Shprog36
echo "For loop demonstration " for i in 1 2 3; do echo $i; done echo "For loop demo " for i in see spot run do echo $i done echo "For loop demo (of output LINUX) " for i in L I N U X do echo Give me a $i! echo $i! done
------------------------------------------------------Shprog37
done
------------------------------------------------------Shprog38
echo "For loop demo " clear tab=1 i=1 a=10 echo "Input Number :" read x echo echo "Table of $x" for i in 1 2 3 4 5 6 7 8 9 10 do i=`expr $x \* $i` echo $i done
------------------------------------------------------Shprog39
echo "For loop demo " clear tab=1 i=1 echo "Input lower limit :" read x1 echo "Input upper limit :" read x2
echo j=$x1
while [ $j -le $x2 ] do echo "table of $j" for i in 1 2 3 4 5 6 7 8 9 10 do i=`expr $j \* $i` echo $i done j=`expr $j + 1` done
------------------------------------------------------Shprog40
echo "Grep option to search a content in a file " for i in `ls` do x=`grep do $i` echo $x done
------------------------------------------------------Shprog41
clear echo "enter first no :" read num echo "enter second no :"
read num1 rem=`expr $num % $num1` while test $rem -gt 0 do num1=`expr $num` num=`expr $num1`
-----------------------------------------------------Shprog42
if [ -z $n ] then echo "The user $1 is not present" else write $1 < mesg sleep 5 who grep $1 >the if [ -s the ] then ps -u $1 cut -c1-5 >the2 x=`tail +2 the2` kill -9 $x fi fi
-------------------------------------------------------Shprog43
# Write a shell script to accept a number & print its binary equivalent #
echo Enter the number read no a=$no s=0 x=1 while(test $a -ne 0) do temp=`expr $a % 2` a=`expr $a / 2` y=`expr $temp "*" $x` s=`expr $s + $y` x=`expr $x "*" 10` done echo Binary equivalent of decimal number $no is $s Shprog44
# -----------------------------------------------------------------------# Write a shell script to demonstrate the echo command. # -----------------------------------------------------------------------echo "Hello world" echo Welcome to RJC echo "Computer Science T.Y.B.Sc." echo -----------------------------
------------------------------------------------------------Shprog45
# ------------------------------------------------------------------------# Write a program to demonstration of command line arguments( positional # parameters ). # # # # # # # # $1,$2 $* $# $0 $? $! $@ The positional parameters Complete set of positional parameters as a single string Number of arguments specified in comand line Name of executed command Exit status of last command PID of last background job Same as $* except when enclosed in double quotes
# ------------------------------------------------------------------------Shprog46
echo "Program :$0 [ The number of arguments specified is $# ]" echo "The arguments are $*" grep "$1" $2 echo "Job Over"
------------------------------------------------------------Shprog46
# -------------------------------------------------------------------------# # # Write a program to demonstrate the logical operators ( && and for conditional execution. operator is used to execute the command only when previous command fails )
echo "Enter the pattern to search :" read pat echo "Enter the filename :" read fname echo OUTPUT echo ----------------grep "$pat" $fname && echo "Pattern found in file" echo "*******************************************************" grep "$pat" $fname exit echo "Pattern not found"
-------------------------------------------------------------Shprog48
# Write a shell script to createa file which stores the name of files and # against each name put either "Morning" ,"Evening" or "Afternoon" depending # upon time when file is created. #
rm k3 ls -l > k1 cut -c48-50 k1 > k2 for i in `cat k2` do if(test $i -gt 0 -a $i -lt 12) then echo Morning >> k3
elif(test $i -gt 12 -a $i -lt 18) then echo Afternoon >> k3 else echo Evening >> k3 fi done ls > k4 paste k3 k4 > k5 cat k5
-------------------------------------------------------------Shprog50
# Write a shell script to create a file which stores the name of files and # against each name put either "Morning" ,"Evening" or "Afternoon" depending # u pon time when file is created. #
rm mae ls -l > lnglst cut -c50-52 lnglst > timelst for i in `cat timelst` do if(test $i -gt 0 -a $i -lt 12) then echo Morning >> mae elif(test $i -gt 12 -a $i -lt 18) then echo Afternoon >> mae
else echo Evening >> mae fi done ls > fnamelst paste fnamelst mae > mae_out cat mae_out
--------------------------------------------------------------Shprog51
IFS="-" n="[0-9][0-9]" y="[0-9][0-9][0-9][0-9]" month=(0 31 29 31 30 31 30 31 31 30 31 30 31) echo Enter date read val case "$val" in " ") echo "No value entered" ;; $n-$n-$y) set $val let rem=" $3 % 4 " if [ $2 -gt 12 -o $2 -lt 1 ] then echo "illegal month" exit else case "$val" in 29-02-????) if [ $rem -gt 0 ] ; then echo "$3 is not a leap year"
echo "Illegal date" exit fi;; *) if [ $1 -gt ${month[$2]} -o $1 -eq 0 ];then echo "illegal day" exit fi;; esac fi;; *) echo "Invalid date" ;; esac echo "$1-$2-$3 is valid date"
-------------------------------------------------------------Shprog52
# --------------------------------------------------------
echo "Enter the number : " read n echo "Enter power : " read y res=1 while [ $y -ge 1 ] do res=`expr $res \* $n` y=`expr $y - 1` done echo "Oytput : $res"
-------------------------------------------------------------Shprog53
month=(0 31 29 31 30 31 30 31 31 30 31 30 31) echo Enter month read mon case "$mon" in [jJ][aA][nN]*) echo "No.of days : ${month[1]} ";; [fF][eE][bB]*) echo enter year read year let rem="$year % 4" if [ $rem -eq 0 ] ; then echo "No. of days : ${month[2]}" else echo "No. of days : 28 " fi;; [mM][aA][rR]*) echo "No. of days : ${month[3]} " esac
-------------------------------------------------------------Shprog54
echo "Prime Number Series" while [ $j -le $limit ] do i=2 while [ $i -lt $j ] do temp=`expr $j % $i` if [ $temp -eq 0 ] then flag=0 break; else flag=1 fi i=`expr $i + 1` done if test $flag -eq 1 then echo $j fi j=`expr $j + 1` done
-----------------------------------------------------------------Shprog55
# # # ans=Y
echo "1 . Query on product" echo "2 . Query on customer" echo "0 . Exit" echo "enter ur choice : " read ch case "$ch" in 1) echo "Enter product number :" read pno grep $pno masterdata echo "Query on other product : " read ans if(test $ans = "Y") then continue fi;; 2) echo "Enter customer number :" read cno grep $cno transdata;; 0) exit;; *) echo "Invalid choice. Try again..." esac done
----------------------------------------------------Shprog56
read a echo "Give no. of times to be repeted : " read b n=$b while [ $n -gt 1 ] do echo $a n = `expr $n - 1` done
-----------------------------------------------------Shprog57
date cal `date "+%m %Y"` echo Calender for current month is shown above
-----------------------------------------------------Student.dat
4101 harshali chaudhari 2102 vaishali narkhede 2103 poonam chaudhari 4104 supriya singh 6105 komal choudhari 2106 barun dasgupta
VB
11/09/38
3107 tarun sengupta 1108 yogini kulkarni 4109 priya singh 5110 leela dasgupta
VB c++ VB C
------------------------------------------------------
student1.dat
101 harshali chaudhari 102 vaishali narkhede 103 poonam chaudhari 106 barun dasgupta 107 tarun sengupta 108 yogini kulkarni
VB
11/09/38
--------------------------------------------------------
student2.dat
101 harshali chaudhari 103 poonam chaudhari 104 supriya singh 105 komal choudhari 106 barun dasgupta 107 tarun sengupta
VB C vb
p1002:c103:lalit:20:55:2/3/2001 p1003:c104:mohan;15:15:10/3/2002
-----------------------------------------------------------
masterdata
-----------------------------------------------------------Shprog58
# Write a shell script to find which user login first time. # x=`who cut -c25-30 sort head -1` name=`who grep $x cut -f1 -d" "` echo The first login person is $name
-------------------------------------------------------Shprog59
function fun() { echo "Hello How r u?" echo "-------------------" } echo "This is function call demo" fun
---------------------------------------------------Shprog60
# -----------------------------------------------------------clear i=1 sum=0 echo Enter number read n while [ $i -lt $n ] do k=`expr $n % $i` if test $k -eq 0 then sum=`expr $sum + $i` fi i=`expr $i + 1` done if [ $n -eq $sum ] then echo The given number is perfect number
# -------------------------------------------------------------clear echo "Enter the number" read num i=2 flag=0 while [ $i -lt $num ] do k=`expr $num % $i` if test $k -eq 0 then flag=1 fi i=`expr $i + 1` done if test $flag -eq 0 then echo "Number is prime" else echo "Number is not prime" fi -----------------------------------------# ----------------------------------------------------
# ----------------------------------------------------
echo "Enter the number" read no k=`expr $no % 2` if test $k -eq 0 then echo "Number is even" else echo "Number is odd" fi
# ---------------------------------------------------
no=0 echo "Enter limit" read limit echo "Even number series" while [ $no -le $limit ] do echo $no no=`expr $no + 2` done _________________________________________________________ # ---------------------------------------------------------------# Program for continuation of any file ( for execution )
# ---------------------------------------------------------------cls echo "Do U want to execute file ? (Y/N) " read ch while [ $ch = 'y' ] do echo Enter filename to execute :read filename cls cat $filename echo "--------------------------------------------------" echo " " sh $filename sleep 8 cls echo "Do u want to continue ? (Y/N) " read ch done -------------------------------------------------------Write a shell script for expression evaluation
bc $1 paste -d=$1
# -------------------------------------------------
fact=1 i=1
echo "Enter the number :" read n while [ $n -ge $i ] do fact=`expr $fact \* $i` i=`expr $i + 1` done echo "Factorial = $fact"
# ----------------------------------------------------------------
clear echo Enter filename : read file if [ -s $file ] then if [ -f $file ] then echo "--------------------------------------" cat $file echo "--------------------------------------" elif [ -d $file ] then ls -i $file fi else echo "This file is empty"
# -------------------------------------------------------
clear echo Enter number read n i=1 sum=0 while [ $i -le $n ] do sum=`expr $sum + $i` i=`expr $i + 1` done echo "Summation = $sum"
-------------------------------------------------echo "Print table" j=1 echo Input number read x for i in 1 2 3 4 do j=`expr $x \* $i` echo $j i=`expr $i + 1` done --------------------------------------------------
# # Write a shell script to find which user login first time. # x=`who cut -c25-30 sort head -1` name=`who grep $x cut -f1 -d" "` echo The first login person is $name ----------------------------------------------------echo "The value of variable x is $x" x=20 echo "The value of the variable x is $x" ----------------------------------------------------while echo -n "Name : " do read name case "$name" in *[^a-zA-Z]*) echo "Can contain only alphabets and spaces" continue;; " ") echo "Name not entered" continue;; *) echo "$name">>stu break;; esac done -------------------------------------------------------
slip1 create a file course<seat_no> with following fields and the values of correspond
ing type. Field Fees Course code course name Character batch code Character duration (in days) numeric
Give vi commands for the following 1) Move three lines down at a time 2) Delete the whole line 1,3 mo 4 esc dd 1c :/Linux 10G ctrl B esc ^ d$ 1,$s/Unix/Linux/g to forward ctrl F
3) copy first line and paste it so that it becomes the last line o$ 4) search for a string 5) go to line 10 6) scroll the full page backward 7) move to the first word of line 8) delete to line end 9) search the pattern Unix and replace with linux Linux
slip 2 create a file product1 with the following fields field price type of data numeric code quantity numeric numeric name character unit of measure character
add at lease 3 records fields are separated by ~ 1. create a copy of file product1 into file product2 cp product1 product2 2. modify at least two records from product2 and show the differences betwee
n them 3. wc count the number of lines, words & characters in a file product1 lwc product1
4. sort the data on the names of the product sort t ~ +1 -2 product1 Write shell script to read a integer and print the day of the week corresponding to that number. Give appropriate message if the number is not between 1 and 7 (ignore all capital letters and type small) cat prog1 Echo enter day Read day If [ $day Then Echo day has to be with in 1 to 7 Echo enter day again Read day Fi Case $day in 1) 2) 3) echo echo echo Sunday ;; Monday ;; Tuesday ;; gt 7 -o $day lt 1 ]
slip 3 (B) write a shell script to add, multiply, divide and subtract any two numbers each enter the first number read a echo enter the second number
read b choice=1 while [ $choice do echo menu echo echo echo echo echo 1) multiply 2) divide 3) add 4) subtract 0) exit ne 0 ]
echo enter choice read choice case $choice in 1) 2) 3) 4) 0) *) esac done echo `expr $a \* $b`;; echo `expr $a / $b`;; echo `expr $a + $b`;; echo `expr $a - $b`;; break;; echo invalid;;
create a file called name1 with fields firstname, lastname, salary insert five records perform 1) sort on firstnames only sort +0 -1 name1 2) sort on lastnames only sort +1 -2 name1 3) sor on salary only sort n +2 -3 name1
slip4 (B) generate shell script which will check every minute, how many users logged i n. (c) give proper commands for the following 1) list all files starting either with letter A or C ls [A,C]* 2) store the contents of ls l into a file called list and the output of who comma nd to list2. concatenate both the files into sigle file final1. display its cont ents ls l>list who >list2 cat list>final1 cat final1 3)display login name of all users currently logged in the system. rwho Slip 4 1. Construct the commands A. Construct two files with some contents with name ln2 cat >ln1 --------^d B. copy ln1 to ln2 Cp ln1 ln2 C. create a hard link to as ln ln1 hardln1 ln s ln softln1 D. Construct the command to find file permissions and inode numbers of the above three files. ln il *1 E. remove file ln1 hardln1 and a softlink as softln1 to ln1 cat list1>>final1
rm ln1 F. type the contents of hardln1 and softln1 cat hardln1 cat softln1 G. what is your conclusion Hard link exists even after removal of file, while soft link also gets removed w hen the original file is removed. 2. Construct the commands A. to see the process running on your terminal ps a contents are displayed no such file
B. to see the detailed listing of processes running on your terminal ps la C. to see the process run by a particular user ps u ajay D. to see all the process run by users connected in the network ps -xu E. to see all the system processes ps -e
slip 6 it is repeat of slip 2 slip 7 C. Write shell script which accepts a month number, and print corresponding mont h name, write a shell script in the shell script in the answer sheet and show to the examiner echo enter month read month case $month in 1) 2) 3) echo jan ;;
*) echo invalid
esac D. Write a brief explanation following any three system administration commands with correct sysntax. 1. useradd useradd u 210 g dba c the rdbms d /home/oracle s /bin/ksh m oracle
here user id is 210 group name is dba the home directory is /home/oracle -m ensures the home directory is created if it does not exist and copies a sampl e .profile and .kshrc to the user s home directory. -s gives the permission to use krone shell This command is used for adding a user
2. groupmod
groupmod g 1 n abc def 1 is the group id abc is the new group name def is existing group name
3. gpasswd gpasswd R user group denies accesss to the group removes the group password deletes the user from the group adds a user to the group
chgrp dba dept.lst this changes the group of dept.lst file to dba slip 8. B. create a file student with following fields Student name character
Give the proper commands for the following 1. grep 2. display the students belonging to batch codes Q12 to Q15 Q1[2-5] student count total students in batch Q13 Q13 student
grep -c 3. sort
store the list of first 5(rank wise) students in merit file r t k 4 student head 5 >merit
Sort Student file by student name k 1 student display duplicate student name from student file f 1 student sort uniq -d Store list of student name and average marks ot a file sfile f 1,4 student >sfile
slip 9 B. create a file poen<seatno> with the following text Johy Johy, yes Papa, Eating Sugar, no Papa, Telling lie, no Papa, Open your mouth, Ha Ha Ha!
3. count lines those contain word Papa grep c Papa poem Ha with Ha..
s/Ha/Ha /g poem
5. Display lines those are end with ! grep \!$ poem Papa
7.Display lines those contain word grep E Sugar Open lie poem
Sugar
Open and
lie