Systems lab MCCS1.8Cycle-11.unix commands:a. Text processing and backup utilities:1. head : It displays the first few line...
[root@dcalabunixserver ~]# head aaai am a good girlhellohw r ui am finehow is itare there any thingindia is mycountyall ar...
Syntax: tail <filename>       It displays last 10 lines.Ex: [root@dcalabunixserver ~]# tail aaacountyall are fineit is bet...
Translate or delete charactersSyntax: $ tr [option] <filename>Ex: $ [root@dcalabunixserver srilu]# cat f3welcome to first ...
Ex : sort studentstudent filename01 vijay 60 9012 anil 70 7532 sujan 65 4004 hari 70 4522 raju 85 505. Cut: Remove section...
-d field separatorSyntax: $ cut -d “:” -f2 <filename>Cut 2nd field in all recordsEx: [root@dcalabunixserver srilu]# cat>bb...
ignore differences in case when comparing      -s, --skip-chars=N            avoid comparing the first N characters      -...
Options:-a      Treat all files as text and compare them line-by-line, even if they do not seem to be text.-b      Ignore ...
< orange---> banana> oringe5,6c5,6< cat< rat---> mat> penComm.: compare two sorted files line by lineSyntax: comm [OPTION]...
read from standard input and write to standard output and filesEx: $ ls -l <filename>  $ ls -l | tee <filename>  $ ls --fu...
Ex: $ find ~ -type d -name “raj”It searches the absolute path of the DirectoriesEx: $ find ~ -type f -name “file1” exce ca...
It searches the 8bytes DirectoriesEx: $ find ~ -type f -i num “1098”It searches the file with inode numberEx: $ find ~ typ...
You can use fgrep to find all the lines of a file that contain a particular word. For example, to listall the lines of a f...
Ex: fgrep dog my*This command would search files with names such as my file, my.hw1, and my stuff in thecurrent directory....
directory$ grep –w <file> - To search for the exact match for the word$ grep –s <file> - To suppress errors$ grep “jai” <f...
It was created in late 70th of the last century. The name was composed from the initial letters ofthree original authors A...
predefined variables in awkall predefined variables are in upper casesFS       - Input field separatorOFS      - Ouput fie...
awk has got 3 sections   1. BIGIN   2. MIDDLE   3. ENDBegin is keyword for the begin section the variable can be assign in...
-| Now is the time for all good men         to come to the aid of their country.         -| to come to the aid of their co...
awk END { print NR } data    Print the even-numbered lines in the data file:awk NR % 2 == 0 dataIf you use the expression ...
# Print all lines between start/stop pairs: awk /start/, /stop/ file# Print all lines whose first field is different from ...
# 000901|Jones|Bill|532-382-0342|234023# ...# type awk -F"|" $2=="Jones"{print $4} filename# Some looping for printouts BE...
$4 != prev {print preva, prevb, prev, sum/n; n=0; sum=0; prev = $4; preva = $1;prevb = $2}$4 == prev {n++; sum=sum+$5/$6}E...
Ex: [root@dcalabunixserver ~]# du srilu4     srilu/d38     srilu/dir2/dir124     srilu/dir244     srilu[root@dcalabunixser...
b. Process utilities:Process: A process is a program that is being executed. In unix multiple processes can runconcurrentl...
3.at: at command allows the user to specify the time when a command is to be executed. Thecommand takes two arguments, the...
-V Display version information.Ex: [root@dcalabunixserver srilu]# w 10:22:43 up 1:07, 2 users, load average: 0.10, 0.02, 0...
chmod ( change mode): The chmod command changes file access permissions for a file.Syntax: chmod mode files       The mode...
Ex: [root@dcalabunixserver srilu]# ls –l-rw---x--- 1 root root 41 Jan 12 07:44 f6[root@dcalabunixserver srilu]# chmod u-w ...
d--------- 2 root root 4096 Jan 12 09:36 d3[root@dcalabunixserver srilu]# chmod 111 d3[root@dcalabunixserver srilu]# ls -l...
Here in the ftp prompt we have to specify special ftp commands.Type a ? or help to   prompt commands.    The following tab...
[mic@dcalabunixserver ~]$ rlogin root   1234563. telnet: It is a command used to communicate with another host.   [mic@dca...
d.File handling utilities:1. pwd (print working directory): Displays the current working directory.Syntax: $ pwdEx: [root@...
Syntax: $ cat <filename>Ex: [root@dcalabunixserver ~]#cat file1Hello..This is my first FileHave a Nice DayByeCat command c...
^d (Save)Display the record number to the particular fileSyntax: $ cat –n <filename>Ex: [root@dcalabunixserver ~]# cat -n ...
gfhdghjhgdfuhdijhdjfjik[root@dcalabunixserver ~]# cat -s f6gdfahfjgfhdghjhgdfuhdijhdjfjik[root@dcalabunixserver ~]# cat f5...
2010-11hgjfdhsdjfhvidfsdklfjgvijgdfahfjgfhdghjhgdfuhdijhdjfjik3.CC command: used to compile one or more C source files.Syn...
$ls -d : It Displays the present working Directory.$ls -i : It Displays the inode numbers of files and Directories$ls -s :...
$ ls -x : It Displays the files and Directories with multiple columnsFor Ex:[root@dcalabunixserver ~]# ls2             ech...
1.       -b                   The file1 move to file2 with                              backup.2.       -f                ...
[root@dcalabunixserver srilu]# lsdir1 dir2 f1 f2 f3[root@dcalabunixserver srilu]# cd[root@dcalabunixserver ~]# mv f4 ./sri...
location.Syntax: $cp [option] <source file> <Destination file>Options ,-a, --archive   same as -dR --preserve=all --backup...
[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f4 f5....new fileEx :[root@dcalabunixserver srilu]# cat f1welcome to adithy...
[root@dcalabunixserver dir2]# cd ..[root@dcalabunixserver srilu]# cp f5 dir2[root@dcalabunixserver srilu]# cd dir2[root@dc...
Ex : $ cp -ir <Directory 1> <Directory 2>Note : It copies the Directory to Directory (including with all files and directo...
Ex: $ rm f1 f2 f3 f4To remove files ForciblySyntax: $ rm [option] <filename>Ex: [root@dcalabunixserver srilu]# rm -f f4[ro...
[root@dcalabunixserver srilu]# lsdir2 f3 f5 f6 f7 f87. touch: The touch command is used to update the timestamp on the nam...
Syntax: $ wc [option] <filename>Options:       -c, --bytes        print the byte counts    -m, --chars        print the ch...
Options:        -b        like --backup but does not accept an argument    -f, --force-remove existing destination files  ...
total 24drwxr-xr-x 3 root root 4096 Jan 11 12:45 dir2-rw-r--r-- 3 root root 41 Jan 12 07:40 f1-rw-r--r-- 3 root root 41 Ja...
2.Soft link:It can be built across the file systemIf the source file is delete we cant retrieve from target fileSyntax : l...
Syntax:$ unlink <filename>Ex: [root@dcalabunixserver srilu]# lsdir2 f1 f3 f5 f6 f7 f8[root@dcalabunixserver srilu]# unlink...
Ex: [root@dcalabunixserver dir3]# mkdir -p d2/d3/d4[root@dcalabunixserver dir3]# lsd2[root@dcalabunixserver dir3]# cd d2[r...
[root@dcalabunixserver aaa]#To change the directory forwardSyntax: $ cd ..Ex: [root@dcalabunixserver aaa]# cd ..[root@dcal...
2. Shell programmingi.AIM: To print the factorial of first n natural numbers.SOURCE CODE:[root@dcalabunixserver srilu]$cat...
ii.AIM: To list the files in the current directory to which the user has read, write andexecute permissions.SOURCE CODE:[r...
fi    fi    fidone[root@dcalabunixserver srilu]$ sh dirlist.sha.out    sample11.txtiii.AIM: perform the following string o...
SOURCE CODE:echo "enter string"cat - |wc -c[root@dcalabunixserver srilu]$ sh len.shenter stringcomputers93. simulate the f...
{w1=w1+tq;t[i]=w1;w[i]=t[i]-st[i];s[i]=s[i]-tq;}}for(i=0;i<n;i++){tw=tw+w[i];tt=tt+t[i];}aw=tw/n;at=tt/n;printf("processts...
b. SJFAIM: Write a C program for SJF CPU scheduling algorithmSOURCE CODE:#include<stdio.h>main(){int i,j,bt[10],n,pt[10],w...
printf(“nbttwtttt”);for(i=0;i<n;i++)printf(“%dt%dt%dn”,bt[i],wt[i],tt[i]);printf(“aw=%dnat=%d”,aw,at);getch();}Input:Enter...
c. FCFSAIM: Write a C program for FCFS CPU scheduling algorithmSOURCE CODE:include<stdio.h>main(){int i,j,bt[10],n,pt[10],...
Input:enter no of jobs3enter bursttime12820output:bt wt tt12 0 128 12 2020 20 40aw=10.666670at=24.00000d. PRIORITYAIM: Wri...
wt[i+1]=bt[i]+wt[i];tt[i+1]=tt[i]+bt[i];w1=w1+wt[i];t1=t1+tt[i];}aw=w1/n;at=t1/n;printf(“nbttproritytwtttt”);for(i=0;i<n;i...
4. write programs for fork, vfork.AIM: Write a C program that illustrates the creation of childprocess using fork( ) syste...
getpid(),getppid());}printf(“ pid %d terminates “,getpid());}Output:original process with pid 3456 and ppid 3525child proc...
printf(“ pid %d terminates “,getpid());}Output:original process with pid 3456 and ppid 3525child process with pid 3457 and...
Upcoming SlideShare
Loading in …5
×

Unix lab manual

7,825 views

Published on

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
7,825
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
369
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Unix lab manual

  1. 1. Systems lab MCCS1.8Cycle-11.unix commands:a. Text processing and backup utilities:1. head : It displays the first few lines of one or more files (page) .Syntax: $ head <filename> It displays the first 10 lines of the file.Ex: [root@dcalabunixserver ~]# cat aaai am a good girlhellohw r ui am finehow is itare there any thingindia is mycountyall are fineit is betterdont do thatwhere are uhello hw r uis it okkwhat is thatthank ubye
  2. 2. [root@dcalabunixserver ~]# head aaai am a good girlhellohw r ui am finehow is itare there any thingindia is mycountyall are fineit is betterSyntax: $ head –n <filename>Ex: [root@dcalabunixserver ~]# head -3 aaai am a good girlhellohw r usyntax: $ cat <filename> | head -n - It display first n linesEx: [root@dcalabunixserver ~]# cat aaa | head -4i am a good girlhellohw r ui am fine2. tail : It displays last few records of one or more file
  3. 3. Syntax: tail <filename> It displays last 10 lines.Ex: [root@dcalabunixserver ~]# tail aaacountyall are fineit is betterdont do thatwhere are uhello hw r uis it okkwhat is thatthank ubyeSyntax: tail –n <filename>Ex: [root@dcalabunixserver ~]# tail -2 aaathank ubyesyntax: cat <filename> | tail -nEx: [root@dcalabunixserver ~]# cat aaa | tail -1byeIf u want to redirect to permanentEx: $ head -20 <filename> |tail -5 > file1 (file1 is newfile)Ex: $ tail +30 <filename> |head -5 > file1 (file1 is newfile)3. tr : Translate characters by characters
  4. 4. Translate or delete charactersSyntax: $ tr [option] <filename>Ex: $ [root@dcalabunixserver srilu]# cat f3welcome to first mtech2010-11[root@dcalabunixserver srilu]# tr "wel" "*"<f3***com* to first mt*ch2010-11Duplicate characters avoid with sequential orderEx: $ tr -s “r” < filenameDelete the charactersSyntax: $ tr -d “r” < filename[root@dcalabunixserver srilu]# tr -d "e"<f6wlcom to adithyacollgof technology4. Sort: sort lines of text files according to the first characterSyntax: sort [option] <filename>Options:-b, --ignore-leading-blanks ignore leading blanks-d, --dictionary-order consider only blanks and alphanumeric characters-f, --ignore-case fold lower case to upper case characters-g, --general-numeric-sort compare according to general numerical value-i, --ignore-nonprinting consider only printable characters-M, --month-sort compare (unknown) < âJANâ < ... < âDECâ-n, --numeric-sort compare according to string numerical value-r, --reverse reverse the result of comparisons
  5. 5. Ex : sort studentstudent filename01 vijay 60 9012 anil 70 7532 sujan 65 4004 hari 70 4522 raju 85 505. Cut: Remove sections from each line of files. 1. Character cuttingSyntax: $ cut -c <filename>First character of the all lines[root@dcalabunixserver srilu]# cut -c 5-10 f6ome toegeechnolEx: $ cut -c1 <filename>To cut the first Character Of the all recordsEx: $ cut -c8 <filename>To cut the 8th character in each lineEx: $ cut -c4, 8 <filename>To cut 4th and 8th Character In each lineEx: $ cut -c4 -8 <filename>To cut 4th to 8th Characters range 2. Field cutting
  6. 6. -d field separatorSyntax: $ cut -d “:” -f2 <filename>Cut 2nd field in all recordsEx: [root@dcalabunixserver srilu]# cat>bbbaaa:fff:hhhhttt:ghh:tgyh:yuuert:hgjjk:hhh[3]+ Stopped cat > bbb[root@dcalabunixserver srilu]# cut -d : -f1 bbbaaatttghh6. Uniq: Remove duplicate lines from a sorted fileSyntax: $ uniq [option] <filename>Options:-c, --count prefix lines by the number of occurrences -d, --repeated only print duplicate lines -D, --all-repeated[=delimit-method] print all duplicate lines delimit-method={none(default),prepend,separate} Delimiting is done with blank lines. -f, --skip-fields=N avoid comparing the first N fields -i, --ignore-case
  7. 7. ignore differences in case when comparing -s, --skip-chars=N avoid comparing the first N characters -u, --unique only print unique lines -w, --check-chars=N compare no more than N characters in linesDisplays only the Duplicate recordsEx: $ uniq -d <filename >[root@dcalabunixserver srilu]# cat>cccaaabbbaaaaaa[7]+ Stopped cat > ccc[root@dcalabunixserver srilu]# uniq -d cccaaaEx: $ uniq -D <filename>Print all duplicate Records and demeliting is done with blank linesEx: $ uniq –c <filename>Prefix lines by the Number of occurrencesEx: [root@dcalabunixserver srilu]# uniq -c ccc 1 aaa 1 bbb 2 aaaDiff: find differences between two filesSyntax: diff [options] from-file to-file
  8. 8. Options:-a Treat all files as text and compare them line-by-line, even if they do not seem to be text.-b Ignore changes in amount of white space.-B Ignore changes that just insert or delete blank lines.[root@dcalabunixserver srilu]# cat>luckyapplebannanaorangepineapplecatrat[9]+ Stopped cat > lucky[root@dcalabunixserver srilu]# cat>keertuapplebananaoringepineapplematpen[10]+ Stopped cat > keertu[root@dcalabunixserver srilu]# diff lucky keertu2,3c2,3< bannana
  9. 9. < orange---> banana> oringe5,6c5,6< cat< rat---> mat> penComm.: compare two sorted files line by lineSyntax: comm [OPTION]... FILE1 FILE2Ex: [root@dcalabunixserver srilu]# comm lucky keertu apple bananabannanaorange oringe pineapplecat mat penrat7. tee : It displays and redirects the same time
  10. 10. read from standard input and write to standard output and filesEx: $ ls -l <filename> $ ls -l | tee <filename> $ ls --full-time | tee -a <filename> - appending existing fileNote: without | (pipe symbol) tee filter don’t works8. FIND COMMANDSIt search for files in a directory hierarchySyntax: find [path...] [expression]/ - root~ - Home Directory. - Present working directoryEx: $ find /bin –type fIt searches the files and directories absolute path of the root.Ex: $ find ~ -type dIt searches the directories and subdirectories in the Home directoryEx: $ find ~ -type lIt searches the linked filesEx: $ find ~ -type f -name “file1”It searches the absolute path of the filename
  11. 11. Ex: $ find ~ -type d -name “raj”It searches the absolute path of the DirectoriesEx: $ find ~ -type f -name “file1” exce cat{};It searches the absolute path of the filename and displays the contents of file.Ex: $ find ~ -type f -name “file1” exce cat {} exce rm{};It searches the absolute path of the filename and displays the content of file, and removes at thesame time.Ex: $ find ~ -type f -perm 644It searches the file under with 644 permissionEx: $ find ~ -type f -perm 644 -exce chmod 640 {};It searches the filename under with permission 644 and change the file permissions to 640.Ex: $ find ~ -type f size 0;It Searches the Zero byte filesLinux: 512 bytes – 1 blockEx: $ find ~ -type f size 100c (Exactly 100 bytes file) $ find ~ -type f size +100c (above 100 bytes file) $ find ~ -type f size -100c (below 100 bytes file)Ex: $ find ~ -type d size 8b
  12. 12. It searches the 8bytes DirectoriesEx: $ find ~ -type f -i num “1098”It searches the file with inode numberEx: $ find ~ type d – inum “1024”It searches the directories with inode numberTime -a – Access -c – Changed -m – ModifiedEx: $ find ~ -type f –a min 30It searches the file before 30 min accessEx: $ find ~ -type f –a time –n/n/+nIt searches the file before few days9. GrepThe grep utilities are a family of Unix tools, including grep, egrep, and fgrep, that performrepetitive searching tasks. The tools in the grep family are very similar, and all are used forsearching the contents of files for information that matches particular criteria. For most purposes,youll want to use fgrep, since its generally the fastestThe general syntax of the grep commands is:Syntax: grep [-options] pattern [filename]
  13. 13. You can use fgrep to find all the lines of a file that contain a particular word. For example, to listall the lines of a file named my file in the current directory that contain the word "dog", enter atthe Unix prompt:Ex: fgrep dog myfileThis will also return lines where "dog" is embedded in larger words, such as "dogma" or"dogged". You can use the -w option with the grep command to return only lines where "dog" isincluded as a separate word: Ex: grep -w dog myfileTo search for several words separated by spaces, enclose the whole search string in quotes, forexample:Ex: fgrep "dog named Checkers" myfileThe fgrep command is case sensitive; specifying "dog" will not match "Dog" or "DOG". You canuse the -i option with the grep command to match both upper- and lowercase letters:Ex: grep -i dog myfileTo list the lines of myfile that do not contain "dog", use the -v option:Ex: fgrep -v dog myfileIf you want to search for lines that contain any of several different words, you can create asecond file (named second file in the following example) that contains those words, and then usethe -f option:Ex: fgrep -f second file my fileYou can also use wildcards to instruct fgrep to search any files that match a particular pattern.For example, if you wanted to find lines containing "dog" in any of the files in your directorywith names beginning with "my", you could enter:
  14. 14. Ex: fgrep dog my*This command would search files with names such as my file, my.hw1, and my stuff in thecurrent directory. Each line returned would be prefaced with the name of the file where thematch was found.By using pipes and/or redirection, you can use the output from any of these commands withother Unix tools, such as more, sort, and cut. For example, to print the fifth word of every line ofmy file containing "dog", sort the words alphabetically, and then filter the output through themore command for easy reading, you would enter at the Unix prompt:Ex: fgrep dog myfile | cut -f5 -d" " | sort | moreIf you want to save the output in a file in the current directory named new file, enter:Ex: fgrep dog my file | cut -f5 -d" " | sort > new file$ grep –n <file> - To display record number$ grep -i<file> - To ignore record$ grep –c <file> - To count in how many records expression$ grep –E <file> - To search for multiple expression$ grep –L <file> - It give the file name and which the regular expression$ grep –r <file> - To search regressively and present working
  15. 15. directory$ grep –w <file> - To search for the exact match for the word$ grep –s <file> - To suppress errors$ grep “jai” <file> - It prints the expressive record which have got the “jai”$ grep –n “jai” <file> - It display the record number and expression what we give “jai”$ grep –in “jay” <file> - It ignore and prints the record “Jay”$ grep –E “jay prem” <file> - It search for multiple expressions and prints the record$ grep –l “jay”* - It displays the filename which the “Jay” expression isAWKAWK is a simple and elegant pattern scanning and processing languageAWK is also the most portable scripting language
  16. 16. It was created in late 70th of the last century. The name was composed from the initial letters ofthree original authors Alfred V. Aho, Brian W. Kernighan, and Peter J. Weinberger. It iscommonly used as a command-line filter in pipes to reformat the output of other commands. Itsthe precursor and the main inspiration of Perl. Although originated in Unix it is available andwidely used in Windows environment too.AWK takes two inputs: data file and command file. The command file can be absent andnecessary commands can be passed as augments. As Ronald P. Loui aptly noted awk is veryunder appreciated language:The main advantage of AWK is that unlike Perl and other "scripting monsters" that it is veryslim without feature creep so characteristic of Perl and thus it can be very efficiently used withpipes. Also it has rather simple, clean syntax and like much heavier TCL can be used with C for"dual-language" implementations. awks favor compared to perl:- awk is simpler (especially important if deciding which to learn first)- awk syntax is far more regular (another advantage for the beginner, even without considering syntax-highlighting editors)- you may already know awk well enough for the task at hand- you may have only awk installed- awk can be smaller, thus much quicker to execute for small programs- awk variables dont have `$ in front of them :-)- clear perl code is better than unclear awk code; but NOTHING comes close to unclear perl codeThe basic function of awk is to search files for lines (or other units of text) that contain certainpatterns. When a line matches one of the patterns, awk performs specified actions on that line.awk keeps processing input lines in this way until it reaches the end of the input filesSyntax : awk [option] ‘selection criteria {action}’ <file>Options : -F - To specify the field separator -f - To invoke the source code {action} - Only the print action
  17. 17. predefined variables in awkall predefined variables are in upper casesFS - Input field separatorOFS - Ouput field separatorNF - Number of fieldsNR - Record numbers or No. of records$ - Fields in awkComparation Operator in awk> - Grater than>= - Grater than equal< - Less than<= - Less than equal== - Equal to!= - Not equal~ - Matching!~ - not matchingLogical Operator&& - AND|| - OR
  18. 18. awk has got 3 sections 1. BIGIN 2. MIDDLE 3. ENDBegin is keyword for the begin section the variable can be assign in begin sectionAll the operator in the middle sections, Middle is not keyword for the middle sectionWhat ever u print every thing in the section, End is the keyword for the end section$ awk ‘/ajay/{print}’<file>It prints the all the records$ awk ‘/ajay|ramu/{print}’<file>To search for multiple expressions and print$ awk ‘NR==4{print}’ <file>To print specific record$ awk ‘NR==3,NR==7{print}’<file>To print range of records$ awk ‘NR>4{print}’ <file>To print all the records which are >4$ awk ‘NR>={print}’ <file>$ awk ‘NR<4{print}’ <file>To print all the records which are <4$ awk ‘NR<=4{print}’ <file>if u want print only specific fields$ awk –F “:” ‘NR==4 {print $1, $3, $4}’ <file>simple awk program emulates the cat utility; it copies whatever you type on the keyboardto its standard output (why this works is explained shortly). $ awk { print } Now is the time for all good men
  19. 19. -| Now is the time for all good men to come to the aid of their country. -| to come to the aid of their country. Four score and seven years ago, ... -| Four score and seven years ago, ... What, me worry? -| What, me worry? Ctrl-d Print the length of the longest input line:awk {if(length($0)> max)max = length($0) } END { print max } data Print every line that is longer than 80 characters:awk length($0) > 80 dataThe sole rule has a relational expression as its pattern and it has no action—so the defaultaction, printing the record, is used. Print the length of the longest line in data:expand data | awk {if x < length()) x =length()} END {print "maximum line length is " x}The input is processed by the expand utility to change tabs into spaces, so the widthscompared are actually the right-margin columns.c Print every line that has at least one field:awk NF > 0 dataThis is an easy way to delete blank lines from a file (or rather, to create a new file similarto the old file but from which the blank lines have been removed).t Print seven random numbers from 0 to 100, inclusive:awk BEGIN {for(i=1;i<=7;i++)print int(101*rand())}a Print the total number of bytes used by files:ls -l files | awk { x += $5 } END { print "total bytes: " x } Print the total number of kilobytes used by files:ls -l files | awk { x += $5 } END { print "total K-bytes: " x + 1023)/1024 } Print a sorted list of the login names of all users:awk -F: { print $1 } /etc/passwd | sort Count the lines in a file:
  20. 20. awk END { print NR } data Print the even-numbered lines in the data file:awk NR % 2 == 0 dataIf you use the expression `NR % 2 == 1 instead, the program would print the odd-numbered linesEXAMPLES# is the comment character for awk. field means column# Print first two fields in opposite order: awk { print $2, $1 } file# Print lines longer than 72 characters: awk length > 72 file# Print length of string in 2nd column awk {print length($2)} file# Add up first column, print sum and average: { s += $1 }END { print "sum is", s, " average is", s/NR }# Print fields in reverse order:awk {for i = NF; i > 0; --i)print $i } file# Print the last line {line = $0} END {print line}# Print the total number of lines that contain the word Pat /Pat/ {nlines = nlines + 1} END {print nlines}
  21. 21. # Print all lines between start/stop pairs: awk /start/, /stop/ file# Print all lines whose first field is different from previous one: awk $1 != prev { print; prev = $1 } file# Print column 3 if column 1 > column 2: awk $1 > $2 {print $3} file# Print line if column 3 > column 2: awk $3 > $2 file# Count number of lines where col3 >col 1 awk $3 > $1 {print i + "1"; i++} file# Print sequence number and then column 1 of file: awk {print NR, $1} file# Print every line after erasing the 2nd field awk {$2 = ""; print} file# Print hi 28 times yes | head -28 | awk { print "hi" }# Print hi.0010 to hi.0099 (NOTE IRAF USERS!) yes | head -90 | awk {printf("hi00%2.0f n", NR+9)}# Replace every field by its absolute value { for (i = 1; i <= NF; i=i+1) if ($i < 0) $i = -$i print}# If you have another character that delimits fields, use the -F option# For example, to print out the phone number for Jones in the following file,# 000902|Beavis|Theodore|333-242-2222|149092
  22. 22. # 000901|Jones|Bill|532-382-0342|234023# ...# type awk -F"|" $2=="Jones"{print $4} filename# Some looping for printouts BEGIN{ for (i=875;i>833;i--){ printf "lprm -Plw %dn", i } exit }Formatted printouts are of the form printf( "formatn", value1, value2, ... valueN) e.g. printf("howdy %-8s What it is bro. %.2fn", $1, $2*$3) %s = string %-8s = 8 character string left justified %.2f = number with 2 places after . %6.2f = field 6 chars with 2 chars after . n is newline t is a tab# Print frequency histogram of column of numbers$2 <= 0.1 {na=na+1}($2 > 0.1) && ($2 <= 0.2) {nb = nb+1}($2 > 0.2) && ($2 <= 0.3) {nc = nc+1}($2 > 0.3) && ($2 <= 0.4) {nd = nd+1}($2 > 0.4) && ($2 <= 0.5) {ne = ne+1}($2 > 0.5) && ($2 <= 0.6) {nf = nf+1}($2 > 0.6) && ($2 <= 0.7) {ng = ng+1}($2 > 0.7) && ($2 <= 0.8) {nh = nh+1}($2 > 0.8) && ($2 <= 0.9) {ni = ni+1}($2 > 0.9) {nj = nj+1}END {print na, nb, nc, nd, ne, nf, ng, nh, ni, nj, NR}# Find maximum and minimum values present in column 1NR == 1 {m=$1 ; p=$1}$1 >= m {m = $1}$1 <= p {p = $1}END { print "Max = " m, " Min = " p }# Example of defining variables, multiple commands on one lineNR == 1 {prev=$4; preva = $1; prevb = $2; n=0; sum=0}
  23. 23. $4 != prev {print preva, prevb, prev, sum/n; n=0; sum=0; prev = $4; preva = $1;prevb = $2}$4 == prev {n++; sum=sum+$5/$6}END {print preva, prevb, prev, sum/n}# Example of using substrings# substr($2,9,7) picks out characters 9 thru 15 of column 2{print "imarith", substr($2,1,7) " - " $3, "out."substr($2,5,3)}{print "imarith", substr($2,9,7) " - " $3, "out."substr($2,13,3)}{print "imarith", substr($2,17,7) " - " $3, "out."substr($2,21,3)} print "imarith", substr($2,25,7) " - " $3, "out."substr($2,29,3)}1. Renaming within the name:ls -1 *old* | awk {print "mv "$1" "$1} | sed s/old/new/2 | sh(although in some cases it will fail, as in file_old_and_old)2. Remove only files:ls -l * | grep -v drwx | awk {print "rm "$9} | shor with awk alone:ls -l|awk $1!~/^drwx/{print $9}|xargs rmBe careful when trying this out in your home directory. We remove files!3. Remove only directoriesls -l | grep ^d | awk {print "rm -r "$9} | shorls -p | grep /$ | wk {print "rm -r "$1}or with awk alone:ls -l|awk $1~/^d.*x/{print $9}|xargs rm -rBe careful when trying this out in your home directory. We remove things!4. Killing processes by name (in this example we kill the process called netscape):kill `ps auxww | grep netscape | egrep -v grep | awk {print $2}`Disk utilities:1.df(disk free): df command reports the number of free disk bloks and inode available on allmounted file systems or on a given name.Syntax: df [option] [file system]Options: h displays information in readable format. i displays information about free inodes.
  24. 24. Ex: [root@dcalabunixserver ~]# du srilu4 srilu/d38 srilu/dir2/dir124 srilu/dir244 srilu[root@dcalabunixserver ~]# du -b srilu4096 srilu/d34137 srilu/dir2/dir18325 srilu/dir216632 srilu2.du(disk usage):du command prints disk usage,i.e.,the number of 512 bytes blocks used byeach named directory and its subdirectory(default is current directory).Syntax: du [option] [directories]Options: a print usage of all files r print “can not open” message if a file or directory is inaccessible. s print only the grand total for each named directoryEx: [root@dcalabunixserver ~]# dfFilesystem 1K-blocks Used Available Use% Mounted on/dev/mapper/VolGroup00-LogVol00 75766816 4990352 66865604 7% //dev/hda1 101086 12167 83700 13% /boottmpfs 513468 0 513468 0% /dev/shm3.mount(mounting file system): mount connect the specified device (which is actually a filesystem) to the directory specifed the member files of the files system mounted becomes themembers of the directory on which they are mounted .Syntax: mount [derivename directory] [option]Options:-r the file system will be mounted as “read Only” the default option is “r/w”4. umount(dismounting file system): “umount” disconnect should be used only after makingsure that the particular file system is not busy that the particular file system is not busy. Unlikethe case of “mount”, you do not have to specify the mount point. Use “sync” before using“umount”.Syntax: umount [device 4name]
  25. 25. b. Process utilities:Process: A process is a program that is being executed. In unix multiple processes can runconcurrently.Users: Typically there are number of users on a unix system. Each user is identified by a uniqueuser name and user-id. Unix uses the user name in several different ways: 1. To report usage of system resources. 2. To display the list of users on the system. 3. To implement system and file security.Usergroups: A user may be part of one or more usergroups.PID: In multiuser environment, there are number of processes that are being executed. To keeptrack of process that is being executed, unix assigns a unique process identification number(PID)to each active process.1.ps (process status): The ps command displays information about the individual processe thatare executing on the system.Syntax: $ps [options]Options: -a reports information about all process -l report information in long formatEx: [root@dcalabunixserver srilu]# ps PID TTY TIME CMD 3138 pts/1 00:00:00 bash 3179 pts/1 00:00:00 ps2. kill: Terminating a process Kill is used to terminate the execution of a background process. The process-id of theprocess to be terminated must be specified with kill command. If process id ‘0 (zero)’ isspecified, all processes in the process are signed.Syntax: $kill <process id>Options: n where n is larger than 0. The process with pid n will be signaled. 0 All processes in the current process group are signaled. -1 All processes with pid larger than 1 will be signaled.Ex: [root@dcalabunixserver srilu]# kill -9 0
  26. 26. 3.at: at command allows the user to specify the time when a command is to be executed. Thecommand takes two arguments, the time at which the command is to be executed, and thecommand to be executed.Syntax: at time[date] [increment]Ex: [root@dcalabunixserver srilu]# [root@dcalabunixserver srilu]# at 12.30pm jan 13at> cat f3at> <EOT>job 3 at 2011-01-13 12:304.nice: Unix also allows the user to specify the priority of commands. The nice command is usedto run a command at a specified scheduling priority.Syntax: nice [-increment] command [argument]Ex: [root@dcalabunixserver ~]# nicenice05. who: who command shows who is logged on,as well as information about the system.Syntax: $whoEx: [root@dcalabunixserver srilu]# whoroot :0 2011-01-13 09:26root pts/1 2011-01-13 09:49 (172.16.6.250)6.who am i: Displays current user.Syntax:$who am iEx: [root@dcalabunixserver srilu]# who am iroot pts/1 2011-01-13 09:49 (172.16.6.250)7.w: w command printf summaries of system usage, currently logged-in users, and what they aredoing.Syntax: w [option] [user]Options: -u Ignores the username while figuring out the current process and cpu times. To demonstrate this, do a "su" and do a "w" and a "w -u". -s Use the short format. Donât print the login time, JCPU or PCPU times. -l Display information in long format.
  27. 27. -V Display version information.Ex: [root@dcalabunixserver srilu]# w 10:22:43 up 1:07, 2 users, load average: 0.10, 0.02, 0.01USER TTY FROM LOGIN@ IDLE JCPU PCPU WHATroot :0 - 09:26 ?xdm? 13.03s 0.11s /usr/bin/gnome-sessionroot pts/1 172.16.6.250 09:49 0.00s 0.07s 0.00s w8. File level security: Unix uses an elaborate method of file access permissions to maintain file security. File access permissions: Each file and directory has an 1. An owner: The user who created the file. 2. A group: A group of users have access to the file. 3. Others: Other users of the system. The permissions can be granted or denied to these three classes of users. Three types of file access permissions are there, they are read: A file can be read, displayed on terminal, copied and compiled. write: A file can be read modified and deleted. executed: A file can be executed as a program.They are represented as-rwx------drwxr--r---rwx-w--w-- - Filed - Directoryw - Wrirer - Readx - ExecutableNote: Without write permissions we can’t copy, remove, modify, move, cratedrwxrwxrwx777Directory – 777File – 666Default Directory Permissions – 755Default File Permissions – 644Read –4Write –2Executable –1Total Permissions 7
  28. 28. chmod ( change mode): The chmod command changes file access permissions for a file.Syntax: chmod mode files The mode is the permission to be assigned. Mode can be specified in two ways 1. Numeric Method 2. Symbolic Method1. Numeric Method:Syntax: $ chmod [permissions] <file/Directory>Ex: [root@dcalabunixserver srilu]# ls -ltotal 24drwxr-xr-x 2 root root 4096 Jan 12 09:36 d3-rw-r--r-- 2 root root 41 Jan 12 07:40 f8[root@dcalabunixserver srilu]# chmod 624 f8[root@dcalabunixserver srilu]# ls -ltotal 24drwxr-xr-x 2 root root 4096 Jan 12 09:36 d3-rw--w-r-- 2 root root 41 Jan 12 07:40 f82. Symbolic Method:User – uGroup – gOthers – oAll –aRead – rWrite – wExecute – xSyntax: $ chmod [options] <File/Directory>Ex: [root@dcalabunixserver srilu]# ls -ltotal 24drwxr-xr-x 2 root root 4096 Jan 12 09:36 d3-rw-r--r-- 1 root root 31 Jan 10 13:22 f3 [root@dcalabunixserver srilu]# chmod o=rwx,g=r,u=x f3[root@dcalabunixserver srilu]# ls -ltotal 24drwxr-xr-x 2 root root 4096 Jan 12 09:36 d3---xr--rwx 1 root root 31 Jan 10 13:22 f3To Add Write permission to Group and OthersEx: [root@dcalabunixserver srilu]# ls -ltotal 24drwxr-xr-x 2 root root 4096 Jan 12 09:36 d3[root@dcalabunixserver srilu]# chmod g+w,o+w d3[root@dcalabunixserver srilu]# ls -ltotal 24drwxrwxrwx 2 root root 4096 Jan 12 09:36 d3To Remove the Write Permission to User
  29. 29. Ex: [root@dcalabunixserver srilu]# ls –l-rw---x--- 1 root root 41 Jan 12 07:44 f6[root@dcalabunixserver srilu]# chmod u-w f6[root@dcalabunixserver srilu]# ls –l-r----x--- 1 root root 41 Jan 12 07:44 f6To Remove the Write and execute permissions to Group and OthersEx: [root@dcalabunixserver srilu]# ls -ltotal 24drwxrwxrwx 2 root root 4096 Jan 12 09:36 d3[root@dcalabunixserver srilu]# chmod g-wx,o-wx d3[root@dcalabunixserver srilu]# ls -ltotal 24drwxr--r-- 2 root root 4096 Jan 12 09:36 d3Append the Write permissions to allEx: $chmod u+w, g+w, o+w Dir1 (or) $chmod a+w Dir1UMASK (User File Creation Mask)- cuting, remove, hiddenBy Default umask value is 022Directory File777 666022 022755 644 Permissions Umask File/Directory number 0 --- 1 --x 2 -w- 3 -wx 4 r-- 5 r-x 6 rw- 7 rwxEx: [root@dcalabunixserver srilu]# ls -ltotal 24
  30. 30. d--------- 2 root root 4096 Jan 12 09:36 d3[root@dcalabunixserver srilu]# chmod 111 d3[root@dcalabunixserver srilu]# ls -ltotal 24d--x--x--x 2 root root 4096 Jan 12 09:36 d39. chown (change owner) & chgrp (change group): chown changes file ownership andreassign the ownership of the file from one user to another.Syntax: chown [option] newowner filenameOptions: -c, --changes-like verbose but report only when a change is made -h, --no-dereference-affect each symbolic link instead of any referenced fileEx: [root@dcalabunixserver srilu]# ls -l---xr--rwx 1 root root 31 Jan 10 13:22 f3[root@dcalabunixserver srilu]# chown mic f3[root@dcalabunixserver srilu]# ls -l---xr--rwx 1 mic root 31 Jan 10 13:22 f3 Chgrp also changes ownership. It changes the group ownership of the file.Syntax: chgrp [option] groupname filenameOptions:-c, --changes- like verbose but report only when a change is made-h, --no-dereference-affect each symbolic link instead of any referenced file --preserve-rootfail to operate recursively on â/â -f, --silent, --quiet suppress most error message -R, --recursive operate on files and directories recursivelyEx: [root@dcalabunixserver srilu]# ls -l---xr--rwx 1 mic root 31 Jan 10 13:22 f3[root@dcalabunixserver srilu]# chgrp mic f3[root@dcalabunixserver srilu]# ls -l---xr--rwx 1 mic mic 31 Jan 10 13:22 f310.newgrp : changes group.Syntax: newgrp group[root@dcalabunixserver srilu]# newgrp micc.Networking commands: 1. ftp:This command is used to connect to any other computer on your network running ftp. Start it with the following [root@dcalabunixserver ~]# ftp ftp ftp> ?
  31. 31. Here in the ftp prompt we have to specify special ftp commands.Type a ? or help to prompt commands. The following table lists the most frequently used commands Command Result ascii Uses, ascii as a file transfer type bell Rings the bell when file transfer is completed Binary Uses binary as file transfer type quit or bye Terminates ftp session close Ends ftp connection with remote machine, but keeps local ftp program running cd Changes directory on remote machine get filename Gets the filename from remote machine pwd Lists the current working directory on remote machine ftp> open 172.16.6.100 Connected to 172.16.6.100. 220 dcalabunixserver FTP server (Version 5.60) ready. Name (172.16.6.100:mic):sri 530 please specify password Password: 530 login successful. Remote system type is UNIX. ftp>pwd 313 “home/mic” ftp>ls -rw-r--r-- 1 mic mic 109 Aug 18 18:46 A -rw-r--r—1 mic mic 113 Aug 18 18:49 a.c -rw-r--r—1 mic mic 76 Oct 21 13:09 add1.sh drwxr-xr-x 2 mic mic 4096 Jan 5 13:28 Desktop ftp> quit 221 Goodbye.2. rlogin (Remote login):The rlogin command allows you to remotely login another computer on your network.
  32. 32. [mic@dcalabunixserver ~]$ rlogin root 1234563. telnet: It is a command used to communicate with another host. [mic@dcalabunixserver ~]$ pwd /home/mic [mic@dcalabunixserver ~]$ telnet 172.16.6.100 Trying 172.16.6.100... Connected to 172.16.6.100 (172.16.6.100). Escape character is ^]. Red Hat Enterprise Linux Server release 5.5 (Tikanga) Kernel 2.6.18-194.el5 on an i686 login: mca0933 Password: Last login: Tue Oct 19 09:40:20 from 172.16.6.31 [mca0933@dcalabunixserver ~]$ pwd /home/mca0933 [mca0933@dcalabunixserver ~]$ exit Connection closed by foreign host. [mic@dcalabunixserver ~]$ pwd /home/mic4. Finger: This command displays information about system users. Options: -s display the output in short form -l display th output in long form -m couese finger to search only in login names that match with argument name. Ex: [mic@dcalabunixserver ~]$ finger mic Login: mic Name: (null) Directory: /home/mic Shell: /bin/bash On since Wed Jan 12 10:51 (IST) on pts/1 from 172.16.6.250 No mail. No Plan. [mic@dcalabunixserver ~]$ finger -s mic Login Name Tty Idle Login Time Office Office Phone mic pts/1 Jan 12 10:51 (172.16.6.250)5. Wall: For broad casting messages. [root@dcalabunixserver ~]# wall hai Broadcast message from root (pts/2) (Wed Jan 12 13:20:15 2011): hai
  33. 33. d.File handling utilities:1. pwd (print working directory): Displays the current working directory.Syntax: $ pwdEx: [root@dcalabunixserver ~] # pwd /root2. cat command:displaying and creating filesTo Create a File:Syntax: $ cat < [option] > <filename>The option can be any one of the belowS.no Option Function1. -v It is used to display non printable characters.2. -n It is used to numbering lines in output.3. -b It used to number nonblank output lines.4. -e It display $ at end of each line.5. -A Shows all6. -s never more than one single blank lineEx: [root@dcalabunixserver ~]#cat > file1Hello..This is my first FileHave a Nice DayByeCtrl+d (Save)To View a already existing File:
  34. 34. Syntax: $ cat <filename>Ex: [root@dcalabunixserver ~]#cat file1Hello..This is my first FileHave a Nice DayByeCat command can also be used to accept more than one file as an argument.Syntax: $cat file1 file2Ex: [root@dcalabunixserver ~]#cat f1 f2 This is simple file This is a simple file2The contents of second file are shown immediately after the first file.To append data to an existing fileSyntax: $ cat >> <filename>Ex: [root@dcalabunixserver ~]#cat >> file1Hello..This is my first FileHave a Nice DayByeGood mornigWelcome to new worldTo Create a Multiple file with help of cat commandSyntax: $ cat <filename1 filename2 ...filename (n) >Ex[root@dcalabunixserver ~]#cat >f1 >f2 >f3 >f4Hello....This is file number f4We create multiple files
  35. 35. ^d (Save)Display the record number to the particular fileSyntax: $ cat –n <filename>Ex: [root@dcalabunixserver ~]# cat -n f1 1 welcome to adithya 2 college 3 of technologyTo ignore the blank RecordsSyntax: $ cat –b <filename>Ex: [root@dcalabunixserver ~]# cat -n f4 1 hgjfdh 2 3 sdjfhvidf 4 5 sdklfjgvij[root@dcalabunixserver ~]# cat -b f4 1 hgjfdh 2 sdjfhvidf 3 sdklfjgvijCreate a Hidden fileSyntax: $ cat [option] <filename>Ex: $ cat >.file1[root@dcalabunixserver ~]# cat >.f5haihelloDisplay the record with single blank line.[root@dcalabunixserver ~]# cat f6gdfahfj
  36. 36. gfhdghjhgdfuhdijhdjfjik[root@dcalabunixserver ~]# cat -s f6gdfahfjgfhdghjhgdfuhdijhdjfjik[root@dcalabunixserver ~]# cat f5cat: f5: No such file or directoryfile names with common strings can be displayed using cat as:syntax:$cat file?Ex: [root@dcalabunixserver ~]# cat f?welcome to adithyacollegeof technologywelcome to first mtech2010-11welcome to first mtech
  37. 37. 2010-11hgjfdhsdjfhvidfsdklfjgvijgdfahfjgfhdghjhgdfuhdijhdjfjik3.CC command: used to compile one or more C source files.Syntax: $cc first.c4. ls(list) : It is a command to list the files and directories in the present working Directory$ ls - a : It is a command to display all files and Directories including hidden files and Directories.$ls * : List information about the Files (the current directory by default). Sort entries alphabetically$ls ~ : It list the all Backup files$ls @ : It list the all linked files and Directories
  38. 38. $ls -d : It Displays the present working Directory.$ls -i : It Displays the inode numbers of files and Directories$ls -s : It Displays the sizes in blocks (Files & Directories)$ls -l : It Displays the long listing files and directories in present working directoryListing directory contents:$ ls list a directory$ ls -l list a directory in long (detailed) formatFor example:$ ls -ldrwxr-xr-x 4 vijay user 1024 Jun 18 09:40 WAITRON_EARNINGS-rw-r--r-- 1 kiran user 767392 Jun 6 14:28 scanlib.tar.gz^^^^ ^ ^ ^ ^ ^ ^ ^|| | | | | | | | | ||| | | | owner group size date time name|| | | number of links to file or directory contents| | | permissions for world(others)| | permissions for members of group| permissions for owner of file: r = read, w = write, x = execute -=no permissiontype of file: - = normal file, d=directory, l = symbolic link, and others...ls -ld * List all the file and directory names in the current directory using long format. Withoutthe "d" option, ls would list the contents of any sub-directory of the current. With the "d" option,ls just lists them like regular files.$ ls -al : It Displays including hidden and log listing files and Directories$ ls -m : It Displays all files and Directories with separated by comma (,)$ ls -ls : It Displays all long listing Directories$ ls --full-time : It Displays files and Directories with total information date and time$ ls -nl : It Displays the long listing files andDirectories according to modification Time$ ls -rtl : It Displays the file and Directories with reverse order$ ls -R : It Displays the all files and Directories Regressively (order by order)$ ls -l : It Displays the files and Directories in a single column (vertical)
  39. 39. $ ls -x : It Displays the files and Directories with multiple columnsFor Ex:[root@dcalabunixserver ~]# ls2 echocli lockings.c serA echocli.c mani sig.ca.c echoser menud.sh sriadd1.sh echoser.c pollcli.c sser.cadd.sh exam1.c pollser.c strclic.canaconda-ks.cfg exam.c pser.c strclii.c[root@dcalabunixserver ~]# ls -ltotal 16148-rw-r--r-- 1 root root 2 Oct 21 13:46 2-rw-r--r-- 1 root root 109 Aug 18 18:46 A-rw-r--r—1 root root 113 Aug 18 18:49 a.c-rw-r--r—1 root root 76 Oct 21 13:09 add1.shdrwxr-xr-x 2 root root 4096 Jan 5 13:28 Desktop-rw-r--r-- 1 root root 121 Oct 21 13:12 e2.c-rw-r--r-- 1 root root 118 Oct 21 13:17 e3.c4. MOVE COMMANDS:This command is used to move the files and directories one place to another placeSyntax: $ mv [option] <Source file/Directory> <Target file/Directory>Options:S.no Option Function
  40. 40. 1. -b The file1 move to file2 with backup.2. -f The file1 move to file2 with forcibly.3. -if The file1 move to file2 with interactive and forcibly mode.These are basically 3 types1. File to File2. File to Directory3. Directory to Directory1. File to FileSyntax: $ mv [option] <Source file> <Target file>[root@dcalabunixserver ~]# mv old new[root@dcalabunixserver ~]# cat oldcat: old: No such file or directory[root@dcalabunixserver ~]# cat newhellohw r uthis is a bookEx: $mv -b file1 file2Note: The file1 move to file2 with backupEx: $ mv -f file1 file2Note: The file1 move to file2 with forciblyEx: $ mv -if file1 file2Note: The file1 move to file2 with interactive and forcibly mode2. File to DirectorySyntax: $ mv [option] <Source file> <Target Directory>Ex: [root@dcalabunixserver ~]# cd srilu
  41. 41. [root@dcalabunixserver srilu]# lsdir1 dir2 f1 f2 f3[root@dcalabunixserver srilu]# cd[root@dcalabunixserver ~]# mv f4 ./srilu/f4[root@dcalabunixserver ~]# cd srilu[root@dcalabunixserver srilu]# lsdir1 dir2 f1 f2 f3 f4Note: The file1 moves to Directory (Dir1)Ex: $ mv -b file1 Dir1Note: The file1 move to Dir1 with backup modeEx: $mv -f file1 Dir1Note: The file1 move to Dir1 with forcibly modeEx: $mv -if file1 Dir1Note: The file1 move to Dir1 with interactive and forcibly mode.3. Directory to DirectorySyntax: $ mv [option] <Source Directory> <Target Directory>Ex: $ [root@dcalabunixserver srilu]# lsdir1 dir2 f1 f2 f3[root@dcalabunixserver srilu]# mv dir1 dir2[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f4[root@dcalabunixserver dir2]# lsdir1 f2 f3Ex: [root@dcalabunixserver srilu]# cp ./dir2/dir1/* ../cp: overwrite `../f1? y[root@dcalabunixserver srilu]# ls -a. .. dir2 f1 f2 f3 f4Note: The content of Dir1 moves to Dir2Ex: $ mv -b Dir1 Dir2Note: The contents of Dir1 move to Dir2 with backupEx: $ mv -f Dir1 Dir2Note: The contents of Dir1 moves to Dir2 with forciblyEx: $ mv -if Dir1 Dir2Note: The contents of Dir1 moves to Dir2 with interactive and forcibly mode.5. COPY COMMANDS: Like mv command, cp is used to create new files or move the contentsof file to another location . Unlike move, however, cp leaves the original file intact at its
  42. 42. location.Syntax: $cp [option] <source file> <Destination file>Options ,-a, --archive same as -dR --preserve=all --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument -d same as --no-dereference --preserve=link -f, --force if an existing destination file cannot be opened, remove it and try again -i, --interactive prompt before overwrite -H follow command-line symbolic links -l, --link - link files instead of copying -L, --dereference - always follow symbolic links -P, --no-dereferenceThese are basically 3 types1. File to a File2. File to a Dictionary3. Directory to DirectoryFile to FileSyntax : $cp <source file> <Destination file>Ex : [root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f4[root@dcalabunixserver srilu]# cp f4 f5
  43. 43. [root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f4 f5....new fileEx :[root@dcalabunixserver srilu]# cat f1welcome to adithyacollegeof technology[root@dcalabunixserver srilu]# cat f2welcome to first mtech2010-11[root@dcalabunixserver srilu]# cp f1 f2cp: overwrite `f2? y[root@dcalabunixserver srilu]# cat f2welcome to adithyacollegeof technology... Existing fileNote: The content of john file overwrite with venkatEx ; $cp -f venkat kumarNote : It is copy the file forcibly venkat to kumar without any permissionEx : $cp -i venkat gandhiNote : It is copy the file interactive mode venkat to kumar with permissions2. File to DirectorySyntax ; $ cp <source file> <Destination Directory>Ex ; [root@dcalabunixserver dir2]# lsdir1 f2 f3
  44. 44. [root@dcalabunixserver dir2]# cd ..[root@dcalabunixserver srilu]# cp f5 dir2[root@dcalabunixserver srilu]# cd dir2[root@dcalabunixserver dir2]# lsdir1 f2 f3 f5Ex : [root@dcalabunixserver ~]# cp -d f1 srilu[root@dcalabunixserver ~]# cd srilu[root@dcalabunixserver srilu]# lsf1Note : It copys the f1file to srilu Directory with backupEx : [root@dcalabunixserver ~]# cp -bf f1 srilu[root@dcalabunixserver ~]# cd srilu[root@dcalabunixserver srilu]# lsf1Note ; It copys the f1 file to srilu Directory with forcibly backupEx : $ [root@dcalabunixserver ~]# cp -ibf f1 srilu[root@dcalabunixserver ~]# cd srilu[root@dcalabunixserver srilu]# lsf1Note : It copys the f1 file to srilu Directory with backup interactively and forciblyEx : [root@dcalabunixserver srilu]# lsf1[root@dcalabunixserver srilu]# cd[root@dcalabunixserver ~]# cp f1 f2 f3 srilu[root@dcalabunixserver ~]# cd srilu[root@dcalabunixserver srilu]# lsf1 f2 f3Note : It copies the no of file to Directory3. Directory to DirectorySyntax : $ cp <Source Directory> <Destination Directory>Ex : $ cp Dravid GangulyEx : $ cp -r Mody VenkatNote : It copies the Directory to Directory (including all files and Directories)
  45. 45. Ex : $ cp -ir <Directory 1> <Directory 2>Note : It copies the Directory to Directory (including with all files and directories withinteractive mode)Ex : $ cp -rf <Dir 1 > <Dir 2> <Dir 3> <Destination Directory>Note : It copies the multiple Directories with forcibly and recessively mode6. rm(removing a file):The rm command is used to delete a file.To Remove a fileSyntax; $ rm [option] <filename>Options: Remove (unlink) the FILE(s). -f, --force ignore nonexistent files, never prompt -i, --interactive prompt before any removal -r, -R, --recursive remove directories and their contents recursively -v, --verbose explain what is being done By default, rm does not remove directories. Use the --recursive (-r or -R) option to removeeach listed directory, too, along with all of its contents.Ex: [root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f4 f5[root@dcalabunixserver srilu]# rm f5rm: remove regular file `f5? y[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f4To Remove Multiple FilesSyntax: $ rm [option] <filenames >
  46. 46. Ex: $ rm f1 f2 f3 f4To remove files ForciblySyntax: $ rm [option] <filename>Ex: [root@dcalabunixserver srilu]# rm -f f4[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3To Remove Interactive ModeSyntax: $ rm [option] <filename>Ex: [root@dcalabunixserver srilu]# lsdir2 f1 f2 f3[root@dcalabunixserver srilu]# rm -i f3rm: remove regular file `f3? n[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3To Remove DirectorySyntax: $ rm [option] <Directory Name>To Remove all Directories and subdirectoriesSyntax: $ rm -r <Directory Name>Ex: $ [root@dcalabunixserver srilu]# rm -r dir3rm: descend into directory `dir3? yrm: remove directory `dir3/aaa? yrm: descend into directory `dir3/d2? yrm: descend into directory `dir3/d2/d3? yrm: remove directory `dir3/d2/d3/d4? yrm: remove directory `dir3/d2/d3? yrm: remove directory `dir3/d2? yrm: remove directory `dir3? y[root@dcalabunixserver srilu]# lsdir2 dir4 f3 f5 f6 f7 f8To Remove Directories ForciblySyntax; $ rm -rf <Directory Name>Ex: $ [root@dcalabunixserver srilu]# rm -rf dir4
  47. 47. [root@dcalabunixserver srilu]# lsdir2 f3 f5 f6 f7 f87. touch: The touch command is used to update the timestamp on the named file. The time stampthe last time the file was altered or accessed.Syntax: touch [option] filenameOptions:-a change only the access time-c, --no-create - do not create any files-f (ignored)-m change only the modification time-r, --reference=FILE- use this fileâs times instead of current timeEx: [root@dcalabunixserver srilu]# lsdir2 f1 f2 f3[root@dcalabunixserver srilu]# touch f5[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f5Note: If the file name issued as an argument does not eists, touch creates it as an empty file.Ex: [root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f5[root@dcalabunixserver srilu]# touch -c f6[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f58. wc : wc command to determine the length of a given file. By default, the output shows thelength in lines, words, characters.
  48. 48. Syntax: $ wc [option] <filename>Options: -c, --bytes print the byte counts -m, --chars print the character counts -l, --lines print the newline counts -L, --max-line-length print the length of the longest line -w, --words print the word countsEx: [root@dcalabunixserver srilu]# wc f13 6 41 f1no of new lines:Ex: [root@dcalabunixserver srilu]# cat f1welcome to adithyacollegeof technology[root@dcalabunixserver srilu]# wc -l f13 f18. ln(creating links): ln command is used to create links for files and allowing them to beaccessed by different names.Call the link function to create a link to a file.Call the link function to create a link named FILE2 to an existing FILE1 1. Hard link 2. Soft LinkSyntax: ln [option] file1 file2 ln [option] file directory
  49. 49. Options: -b like --backup but does not accept an argument -f, --force-remove existing destination files -n, --no-dereference-treat destination that is a symlink to a directory as if it were a normal file -i, --interactive-prompt whether to remove destinations -s, --symbolic-make symbolic links instead of hard links 1. Hard link: Hard link can be build single file system Hard link can recognized it links same permissions and same size, same i-node number If the data in source is loss we can get it from hard link i-node number is given space allocated i-node numbers can recognized different logical namesSyntax : ln <source file> <target file>Ex: [root@dcalabunixserver srilu]# ls -ltotal 16drwxr-xr-x 3 root root 4096 Jan 11 12:45 dir2-rw-r--r-- 1 root root 41 Jan 12 07:40 f2-rw-r--r-- 1 root root 31 Jan 10 13:22 f3-rw-r--r-- 1 root root 0 Jan 12 07:40 f5-rw-r--r-- 1 root root 41 Jan 12 07:44 f6[root@dcalabunixserver srilu]# ln f2 f1[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f5 f6[root@dcalabunixserver srilu]# ln f2 f7[root@dcalabunixserver srilu]# ls -l
  50. 50. total 24drwxr-xr-x 3 root root 4096 Jan 11 12:45 dir2-rw-r--r-- 3 root root 41 Jan 12 07:40 f1-rw-r--r-- 3 root root 41 Jan 12 07:40 f2-rw-r--r-- 1 root root 31 Jan 10 13:22 f3-rw-r--r-- 1 root root 0 Jan 12 07:40 f5-rw-r--r-- 1 root root 41 Jan 12 07:44 f6-rw-r--r-- 3 root root 41 Jan 12 07:40 f7[root@dcalabunixserver srilu]# ln f2 f8[root@dcalabunixserver srilu]# ls -ltotal 28drwxr-xr-x 3 root root 4096 Jan 11 12:45 dir2-rw-r--r-- 4 root root 41 Jan 12 07:40 f1-rw-r--r-- 4 root root 41 Jan 12 07:40 f2-rw-r--r-- 1 root root 31 Jan 10 13:22 f3-rw-r--r-- 1 root root 0 Jan 12 07:40 f5-rw-r--r-- 1 root root 41 Jan 12 07:44 f6-rw-r--r-- 4 root root 41 Jan 12 07:40 f7-rw-r--r-- 4 root root 41 Jan 12 07:40 f8[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f5 f6 f7 f8[root@dcalabunixserver srilu]# rm f2rm: remove regular file `f2? y[root@dcalabunixserver srilu]# lsdir2 f1 f3 f5 f6 f7 f8
  51. 51. 2.Soft link:It can be built across the file systemIf the source file is delete we cant retrieve from target fileSyntax : ln -s <source file> <target file>Ex: [root@dcalabunixserver srilu]# ln -s f2 f9[root@dcalabunixserver srilu]# ls -ltotal 28drwxr-xr-x 3 root root 4096 Jan 11 12:45 dir2-rw-r--r-- 4 root root 41 Jan 12 07:40 f1-rw-r--r-- 4 root root 41 Jan 12 07:40 f2-rw-r--r-- 1 root root 31 Jan 10 13:22 f3-rw-r--r-- 1 root root 0 Jan 12 07:40 f5-rw-r--r-- 1 root root 41 Jan 12 07:44 f6-rw-r--r-- 4 root root 41 Jan 12 07:40 f7-rw-r--r-- 4 root root 41 Jan 12 07:40 f8lrwxrwxrwx 1 root root 2 Jan 12 08:12 f9 -> f2[root@dcalabunixserver srilu]# lsdir2 f1 f2 f3 f5 f6 f7 f8[root@dcalabunixserver srilu]# rm f2rm: remove regular file `f2? y[root@dcalabunixserver srilu]# lsdir2 f1 f3 f5 f6 f7 f8 f99. unlink: use unlink to delete the name and possibly the file it refer’s to.
  52. 52. Syntax:$ unlink <filename>Ex: [root@dcalabunixserver srilu]# lsdir2 f1 f3 f5 f6 f7 f8[root@dcalabunixserver srilu]# unlink f1[root@dcalabunixserver srilu]# lsdir2 f3 f5 f6 f7 f810. mkdir & rmdir: (Making and Removing directories)mkdir creates the new directory in which we can store files and other directories.Syntax: $ mkdir [option] <Directory name>Options:-m, --mode=MODE set permission mode (as in chmod), not rwxrwxrwx - umask -p, --parents no error if existing, make parent directories as needed -v, --verbose print a message for each created directory -Z, --context=CONTEXT (SELinux) set security context to CONTEXTEx: [root@dcalabunixserver srilu]# mkdir dir3[root@dcalabunixserver srilu]# lsdir2 dir3 f3 f5 f6 f7 f8Create Multiple DirectoriesSyntax: $ mkdir [option] <Directory names>Ex: [root@dcalabunixserver srilu]# lsdir2 dir3 f3 f5 f6 f7 f8[root@dcalabunixserver srilu]# mkdir dir4 dir5[root@dcalabunixserver srilu]# lsdir2 dir3 dir4 dir5 f3 f5 f6 f7 f8Create Multi – level DirectoriesSyntax: $ mkdir -p <Directory names>
  53. 53. Ex: [root@dcalabunixserver dir3]# mkdir -p d2/d3/d4[root@dcalabunixserver dir3]# lsd2[root@dcalabunixserver dir3]# cd d2[root@dcalabunixserver d2]# lsd3[root@dcalabunixserver d2]# cd d3[root@dcalabunixserver d3]# lsd4Create Multiple Sub directoriesSyntax: $ mkdir -p <Directory names>Ex: [root@dcalabunixserver srilu]# mkdir -p dir3/aaa dir4/bbb[root@dcalabunixserver srilu]# cd dir3[root@dcalabunixserver dir3]# lsaaa d2[root@dcalabunixserver dir3]# cd ..[root@dcalabunixserver srilu]# cd dir4[root@dcalabunixserver dir4]# lsbbbrmdir: used to remove directories if they are empty.Syntax:rmdir [option] <directory name>Ex: [root@dcalabunixserver srilu]# lsdir2 dir3 dir4 dir5 f3 f5 f6 f7 f8[root@dcalabunixserver srilu]# rmdir dir5[root@dcalabunixserver srilu]# lsdir2 dir3 dir4 f3 f5 f6 f7 f811. cd(change directory): The cd command enables you to move around with in the file system.Used without arguments it returns to your home directory. To move to another directorydirectory name is required as an argument.Syntax: cd <directory name>To Change the DirectorySyntax: $ cd <Directory name>Ex: [root@dcalabunixserver dir3]# cd aaa
  54. 54. [root@dcalabunixserver aaa]#To change the directory forwardSyntax: $ cd ..Ex: [root@dcalabunixserver aaa]# cd ..[root@dcalabunixserver dir3]#To Move parent Directory (root)Syntax: $ cdEx: [root@dcalabunixserver dir3]# cd[root@dcalabunixserver ~]#
  55. 55. 2. Shell programmingi.AIM: To print the factorial of first n natural numbers.SOURCE CODE:[root@dcalabunixserver srilu]$cat factorial.shecho "Enter n value"read nlet i=1let f=1while [ $i -le $n ]dolet f=f*ilet i=i+1doneecho " factorial of $n is $f"[root@dcalabunixserver srilu]$ sh factorial.shEnter n value5factorial of 5 is 120
  56. 56. ii.AIM: To list the files in the current directory to which the user has read, write andexecute permissions.SOURCE CODE:[root@dcalabunixserver srilu]$ cat dirlist.shls > c# cat cexec < cwhile read linedo if test -f $lite then if test -r $line then if test -w $line then if test -x $line then echo $line fi
  57. 57. fi fi fidone[root@dcalabunixserver srilu]$ sh dirlist.sha.out sample11.txtiii.AIM: perform the following string operations. a. To extract a substring from a given string. SOURCE CODE:[root@dcalabunixserver srilu]$ cat sample.shecho "enter any string"read secho "enter range"read nread mecho "`$s|cut -c $m-$n`"[root@dcalabunixserver srilu]$ sh sample.shenter any stringanushaenter range25Nushb. To find the length of a given string.
  58. 58. SOURCE CODE:echo "enter string"cat - |wc -c[root@dcalabunixserver srilu]$ sh len.shenter stringcomputers93. simulate the following CPU scheduling algorithms.a. Round RobinAIM: Write a C program for ROUND ROBIN CPU scheduling algorithm.SOURCE CODE:#include<stdio.h>main(){int s[10],p[10],n,i,j,wi=0,w[10],t[10], st[10],tq,tst=0;int tt=0,tw=0;float aw at;printf("enter no.of process");scanf("%d",&n);printf("n enter time quanum");scanf("%d",&tq);printf("n enter process&service time");for(i=0;i<n;i++)scanf("%d%d",&p[i],&s[i]);for(i=0;i<n;i++)st[i]=s[i];tst=tst+s[i];for(j=0;j<tst;j++)for(i=0;i<n;i++){if(s[i]>tq){s[i]=s[i]-tq;w1=w1+tq;t[i]=w1;w[i]=t[i]-st[i];}else if(s[i]!=0)
  59. 59. {w1=w1+tq;t[i]=w1;w[i]=t[i]-st[i];s[i]=s[i]-tq;}}for(i=0;i<n;i++){tw=tw+w[i];tt=tt+t[i];}aw=tw/n;at=tt/n;printf("procesststtwtttt");for(i=0;i<n;i++)printf("%dt%dt%dt%d",p[i],st[i],w[i],t[i]);printf("awt=%d",aw);printf("att=%d",at);}Input:enter no of process 3enter time quantum 2enter process&service time142632Output:process st wt tt 1 4 4 8 2 6 6 12 3 2 4 6Awt = 4.000000att = 8.000000
  60. 60. b. SJFAIM: Write a C program for SJF CPU scheduling algorithmSOURCE CODE:#include<stdio.h>main(){int i,j,bt[10],n,pt[10],wt[10],tt[10],t,k,l,w1=0,t1=0;float at,aw;printf(“enter no of jobs”);scanf(“%d”,&n);printf(“enter burst time”);for(i=0;i<n;i++)scanf”(%d”,&bt[i]);for(i=0;i<n;i++)for(j=0;j<n;j++)if(bt[i]<bt[j]){t=bt[i];bt[i]=bt[j];bt[j]=t;}for(i=0;i<n;i++){wt[i+1]=bt[i]+wt[i];tt[i+1]=tt[i]+bt[i];w1=w1+wt[i];t1=t1+tt[i];}aw=w1/n;at=t1/n;
  61. 61. printf(“nbttwtttt”);for(i=0;i<n;i++)printf(“%dt%dt%dn”,bt[i],wt[i],tt[i]);printf(“aw=%dnat=%d”,aw,at);getch();}Input:Enter no of jobs4Enter burst time512820Output:Bt wt tt5 0 512 5 138 13 2520 25 45aw=10.75000at=22.000000
  62. 62. c. FCFSAIM: Write a C program for FCFS CPU scheduling algorithmSOURCE CODE:include<stdio.h>main(){int i,j,bt[10],n,pt[10],wt[10],tt[10],t,k,l,w1=0,t1=0;float at,aw;printf(“enter no of jobs”);scanf(“%d”,&n);printf(“enter burst time”);for(i=0;i<n;i++)scanf”(%d”,&bt[i]);for(i=0;i<n;i++){wt[i+1]=bt[i]+wt[i];tt[i+1]=tt[i]+bt[i];w1=w1+wt[i];t1=t1+tt[i];}aw=w1/n;at=t1/n;printf(“nbttwtttt”);for(i=0;i<n;i++)printf(“%dt%dt%dn”,bt[i],wt[i],tt[i]);printf(“aw=%dnat=%d”,aw,at);getch();}
  63. 63. Input:enter no of jobs3enter bursttime12820output:bt wt tt12 0 128 12 2020 20 40aw=10.666670at=24.00000d. PRIORITYAIM: Write a C Program for priority CPU scheduling algorithm.SOURCE CODE:#include<stdio.h>main(){int i,j,bt[10],n,pt[10],wt[10],tt[10],t,k,l,w1=0,t1=0;float at,aw;printf(“enter no of jobs”);scanf(“%d”,&n);printf(“enter burst time”);for(i=0;i<n;i++)scanf”(%d”,&bt[i]);printf(“enter priority values”);for(i=0;i<n;i++)scanf(“%d”,&pt[i]);for(i=0;i<n;i++)for(j=0;j<n;j++)if(pt[i]<pt[j]){t=pt[i];pt[i]=pt[j];pt[j]=t;k=bt[i];bt[i]=bt[j];bt[j]=k;}for(i=0;i<n;i++){
  64. 64. wt[i+1]=bt[i]+wt[i];tt[i+1]=tt[i]+bt[i];w1=w1+wt[i];t1=t1+tt[i];}aw=w1/n;at=t1/n;printf(“nbttproritytwtttt”);for(i=0;i<n;i++)printf(“%dt%dt%dt%dn”,bt[i],pt[i],wt[i],tt[i]);printf(“aw=%dnat=%d”,aw,at);getch();}Input:Enter no of jobs4Enter bursttime10247Enter priority values4213Output:Bt priority wt tt4 1 0 42 2 4 67 3 6 1310 4 13 23aw=5.750000at=12.500000
  65. 65. 4. write programs for fork, vfork.AIM: Write a C program that illustrates the creation of childprocess using fork( ) system callAlgorithm:1. Start2. Declare pid3. create new process using fork( ) system call4. If pid!=0 then5. Display parent process getpid(),getppid().6. Else7. Display child process getpid().getppid().8. EndSOURCE CODE:#include<stdio.h>int main( ){printf(“original process with pid %d ppid %dn”,getpid() ,getppid());pid=fork();if(pid!=0)printf(“parent process with pid %d ppid %d n”,getpid(),getppid());else{sleep(5);printf(“child process with pid %d ppid %dn”,
  66. 66. getpid(),getppid());}printf(“ pid %d terminates “,getpid());}Output:original process with pid 3456 and ppid 3525child process with pid 3457 and ppid 3456pid 3457 terminatesparent process with pid 3456 and ppid 3525pid 3456 terminatesAIM: Write a C program that illustrates the creation of childprocess using vfork( ) system callAlgorithm:1. Start2. Declare pid3. create new process using vfork( ) system call4. If pid!=0 then5. Display parent process getpid(),getppid().6. Else7. Display child process getpid().getppid().8. EndSOURCE CODE:#include<stdio.h>int main( ){printf(“original process with pid %d ppid %dn”,getpid() ,getppid());pid=vfork();if(pid!=0)printf(“parent process with pid %d ppid %d n”,getpid(),getppid());else{sleep(5);printf(“child process with pid %d ppid %dn”,getpid(),getppid());}
  67. 67. printf(“ pid %d terminates “,getpid());}Output:original process with pid 3456 and ppid 3525child process with pid 3457 and ppid 3456pid 3457 terminatesparent process with pid 3456 and ppid 3525pid 3456 terminates

×