Tuesday, February 10, 2015

Unix Basics

UNIX COMMANDS

1. $LOGNAME               : It displays the current user information
2. $PWD                          : present working directory
3. $DATE                         : It displays the system date & time
4. $clear                          : To clear the screen
5. $cal                              : it current month and year
6. $cal 2000                    : Displays the 2000 year calendar
7. $cal 8 2006                 : displays the 8th month of 2006
8. $exit or logout            : exit from current user account
9. $ who                           : displays the all user in who are currently working on server
10. $finger                       : displays the all user who are currently working on server
                                             with more information
11. Who am I                   : displays current user information
12. Which or where       : displays the location of the given command
                                              Syn: $which pwd
13. Cat                              : is use to create new files or to open exiting files or to
                                             append data to the exiting files
Create: cat >filename
-----------   
-----------cttl+d
Redirect: cat file1 file2 file3 >file4--------àredirect output
Append: cat >>filename--------à single file        $cat file1 file2 file3 >>EMP------à multi files
-----------   
-----------cntl+d
Open file: cat <filename-----àopen single file   $cat file1, file2, file3----------àto open multi files
Cat >.filename---------for hidden files
14. Touch               : It is used to create an empty file i.e. 0 byte file
SYN: $ touch filename
$ touch file1 file2 file3---------à create multiple files
15. rm                    : deleting files or directories
EX
rm filename----------------àdeleting single file
rm -i filename--------------àdeleting files with confirmation
rm file1 file2----------------àdeleting multiple files
rmdir dirname--------------àdeleting the directory but the directory must be empty
rm  -r dirname-------------àdeleting directory recursively (i.e. with tree str)
rm –ri dirname-------------àremove directory with confirmation
rm *   ---------------------à it delets all files
rm  -I *--------------------àdelets all files with confirmation
rm t* ---------------------àit delets whose file name starts with ‘t’
16. mkdir               : creating directories
Syn: $mkdir dirname
Sys: $Mkdir .dirname------------àhidden directory
17. Cd          : change directory
Sys: $cd abc
$pwd------/home/prasanna/abc using above cmd we can come out from abc now we at //home/prasanna
cd..---------------------------àto come out from current directory
cd../..------------------------àparent directory
cd/---------------------------àit changes to root directory
cd ~-------------------------àit changes to home directory


18. cp                              :copy source file to target file

Ex
Cp emp1 emp2----------------------àemp1 tp 2 coping
Cp –I m1 m2-------------------------àoverwrite confirmation? Y
Cp –R source directory to target directory-------cp –R abc xyz
19. mv                               : it is used to rename or move file
Ex: mv exiting filename new filename
           Mv emp .emp----------------------àto hide
          Mv .emp emp--------------------àto unhide
20.ls                       : display, list of all files & directories in a current directory
21.ls|more             : display, list of all files & directories page by page
22. ls –a                 : display, list of all files & directories including hidden files and dirctories also in current directory
23. ls  –r                : display list of all files & directories revers order in a current directory
24. Ls –R                : display list of  all files & directories recursively in a current directory
25. Ls –t                 : display list of all files & directories according to date of creation in a current directory
26. Ls –F                : display all list of files & directories, link files, .exe files in a current directory
27. Ls-x                 : display all list of files & directories according to width wise in a current directory
28. Ls-L                  : display all list of files & directories in a current directory in a long list i.e. 9 fields
 1) File types
[1) -- For regular file ii) d—for dir file III) L—for link file IV) b—for block of filesV) c— for char files] [here IV, V is device files]
2) File permissions 3) no. of links 4) owner name 5) group name 6) file size in bytes 7) Date 8) time 9) filename

30. cmp                  : it compares two files char by char
Sys: cmp file1 file2       
Ex: a1: Hello Good Morning
               a2: Hello Good Evening
    If two lines are same then return nothing
     If two files are are different then it displays line number with character position
31. comm.              : It display common lines b/w 2 files
           Syn: Comm File1 file2
32. diff                               : it display different lines b/w 2 files
33. pg                    : it display the file contents page by page
                   Syn: $Pg filename
34. more                : it also display the file contents page by page
                   Syn: $more filename
34. head       :it display the 1st n lines from the file
Sys: $ head –n filename
35. tail                      : it display the last n lines from file
                   Syn: tail –n filename
   Tail +n filename----àit indicates nth line to end of the line 
   Ex: tail +30 file (in this file total no of records is 100) it displays the records from 30th to 100
36. wc           : it counts the no of lines, words, chars in a given file.
                   Syn: $wc filename
i) wc –l filename------------------àit gives the no of lines in a given file
ii) wc –w filename---------------àit gives the no of words in a given file
III) wc –c filename---------------à it gives no. of char in file
iv) wc -lw filename--------------à it gives the no of lines and character in a given file

37. WILD CARD CHARCTERS or META CHARCTERS
i)   ‘*’--------àit matches ‘0’ or more chars
ii)  ‘?’ -------àit matches any single chars
iii) [    ] ---àit matches any single chars in the given list
iv) ‘–‘------àit matches any single char in the given range
  • 1)    ls  t*---------------àit list the files starts with ‘t’
  • 2)    ls  *s  -------------àit list the files that ends with ‘S’
  • 3)    ls b*k--------------àit list the files starts with ‘b’ and ends with ‘k’
  • 4)    ls  a?--------------àit list the 2 characters filename 1st later fallowed by ‘a’ and second letter is any one character
  • 5)    ls[bknt]-----------àit list the files starts with ‘b’ or ‘k’ or ‘n’ or ‘t’
  • 6)    ls [abcdefgh] or ls[a-h]*--àlist the files, first char b/w ‘a’ to ‘h’
  • 7)    ls [b-k][p-t][d-n]*---------à it list the files the 1st character ‘b’ to ‘k’ 2nd char ‘p’ to ‘t’ 3rd char ‘d’ to ‘n’     after that any no of characters
38. grep             : [globally search a regular expression and print it]
Is used for to search a string or regular expression in a given file(s)
I) Eg: $ grep prasanna sample
O/p: 2nd line
5th line
7th line
                    ii) Eg: $grep prasanna a1, a2, a3:
                   a1:------
                   a2:------
a3:------
                   iii) $ grep techno *------àit searches for techno in current dir files (all files)
          iv) $grep techno  sample-----àit searches for more than one word
We kept it in “   “
         v) $grep “techno soft” sample
grep cmd options
grep –i techno sample-----------------------àignore case sensitive
$ grep –c techno sample-----------------------àcount no of lines
$grep –n techno sample-----------------------àprint along with the line numbers
$grep –l techno *------------------------------àlist only file names
$grep –v “techno soft” sample---------------ànot matches print the lines
$grep –ci techno sample----------------------àIgnore case sensitive found no of lines
$grep “techno *” sample---------------------àpattern
Regular expression: any string contains wildcard charcter knows as regular expression or pattern
            These patterns are of 3 types:
Charctor pattern: the default pattern  is char pattern only
i) $grep “techno *” sample
ii) $grep “b [aeiou] ll” sample
iii) $grep “b..d” sample---ài.e. or matches any single charctor
Word pattern :/<    />
                   /< -------àstart of the word
                   />------àend of the word
Grep “/<techno/>” sample ------------ào/p: techno
Grep “/<techno” sample----------------ào/p: techno soft
                                                   -----------------ào/p: techno 123
Grep “techno/>” sample              ----ào/p: hellotechno, abctechno
Grep “/< [0-9][0-9][0-9][0-9]/>” sample--------------àit display 4 digits       (i.e.1234, 4567)

Line pattern: ^----------starts of the file
                                                $----------ends of the file
Ex: grep “^d” sample---------------àit display the line starts with‘d’
          Grep “^the” sample-----------------àit list the lines start with ‘the’
          Grep “^/<the/>” simple ----------àsample the line exactly start with ‘the’
          Grep “t$” simple-------------------àlist the line ends with‘t’ or last char is‘t’
           Grep “[0-9] $” sample------------à display the line ends with 0 to 9 digit
Grep “^ [bkt]” sample------------àlist the line starting with ‘b’ or ‘k ‘or’t’
Grep “^ [^bkt]” sample----------àlist the line which is not start with ‘b’ or ‘k’ or‘t’
Grep “”^UNIX$” sample ---------àdisplay the line having only word ‘Unix’
Grep “^…. $”----------------------àlist the line which contains ‘4’ characters   
(.)----------------------------------àrepresent single charctor
Grep “^.”------------------------àSample it list all lines
Grep “/.” Sample: --------------àit lists the line start with (.)
We use \ to search *, $, ^ as a charctor-------à i.e.\*,|^,\$
Grep “^$” sample--------------à it list empty lines
Grep –c “^$” sample----------àcounts no of empty lines in a file
Grep –v “^$” sample----------àprint not matches (i.e. not empty) lines
Grep –v “^$”sample >temp
Mv temp sample-------------------àhere both are delete empty files
39. fgrep      : it is used for search multiple strings but it doesn’t allow to search regular expression
     $grep “hello
                >techno
          >UNIX”sample----------àit searches for hello or techno str UNIX
40. egrep               : it is combination of grep and fgrep
   $egrep “hello
            >hello
          >UNIX”sample       $egrep “^$” sample
41. Sed                       : to replace a string
$ sed “s/existing string/new string/g” filename--àsed is used to find and replace and grep is for find print
i) $sed “s/Unix/Linux/gi “madhav: -------------à ‘i ‘for case sensitive
ii) $sed “s/^Unix/Linux/gi”----------------------à whatever lines starting with UNIX are replaced by Linux
iii) $sed “s/^$/I like Unix/g I” sample--------àempty string are filled with ‘I like UNIX’’
iv) $Sed “s/Unix//g I” sample-----------------àit search UNIX if found replace with ‘nothing’ (empty)
42. tr                     : to translate a charctor
i) tr “a” “p” <s--------------------à it read data from sample and ‘a’ is replaced by ‘p’
ii) tr “aeiou” “AEIOU”<sample----àreplace char by char
iii) tr “,” “lt” <emp----------------àwhenever “,” is there replace with tab space
          iv) tr “[a-z]” “[A-Z] <Siva--------à converts hole file into uppercase
43) Cut         : it is used for to retrieve required fields and characters from a given file
Ex: madhav is good boy--à18 chars
Cut –f 2-5 madhav---ào/p: adha
Cut –c 1-10 madhav
Cut –c 5-10, 15-20 madhav-------àfor every line 5-10, 15-20 characters
44) Paste     : is used for to join two or more files horizontally by using delimiter
Cat >states                                          cat >cities            paste –d “:”states cities>tr filename
AP                                                      Hyderabad               AP: Hyderabad                  
Tamilnadu                                            madras                   Tamilnadu: madras
Karnataka                                            Bangalore                Karnataka: Bangalore        
Kerala                                                 Trivandrum
Maharashtra                                         Bombay
45) Sort        : it is used for to sort the file content. By default it sorts file contents based on ASCII values-àdefault is ascending
Sort sample
i) sort –r sample------àdisplays descending order
ii) sort –u sample-----àit displays unique lines in the given file
iii) sort –n file----à’N” numeric comparisons
iv) sort –nur file
v) sort sample >temp
$mv temp sample
Sorting the data field by field
+pos--àstarting field
-Pos--àending field (optional)
i) Sort –f +pas1 –pas2 filename
ii) Sort –f +1 -3 filename-----àstarting from end before 3
iii) Sort –fn +2 -3 file ------àit gives only numbers
46) Uniq       : it displays unique lines in the given file but the file contents should be in sort order
Ex:file1         i) $ uniq file                  ii) $uniq –u filename--àit eliminates duplicates Aaaaaa
Aaaaaa         Aaaaaa                             ccccc
Aaaaaa         cccccccc                            ddddd
Ccccccc         dddddd                             Ppppp 
Ddddd           hhhhhh                             ttttttt           
Hhhhh           pppppp
Hhhhh           ttttttttt
Ppppp
Ttttttt
iii) $ Uniq –d filename----displays only duplicated lines   IV) uniq –c filename-----àit counts how many times lines duplicated
                                                                                                                                                                                           Aaaaaa-----2
                                                                       Cccccccc----1
V) $ uniq –u file >temp
$ mv temp filename
Delete duplicated lines from file                         Ddddd-----1
                                                              Hhhhhh---2
                                                              Ppppp-----1
                                                              Ttttttt-----1
47)piping(|)     : it is used for to combine 2 or more cmds |take left side o/p to right side cmd as i/p
i)  $who |wc –l---------àcount total no of lines (files) in current directory
ii) $ ls|wc –l------------àdisplays total no of subdirectories in the current directory
iii) ls –l |grep “^d”----àdisplays total no of subdirectories who stats with line no‘d’
iV) $head -30 sample|tail +20 sample------àdisplay the the lines from 20 to 30 from given file
v) $ grep UNIX stud | cut –f 2, 3|sort filename -----àdisplay UNIX students names & ph no in ascending order
48) $tee            : it is used to for to write data to the file as well as to the screen
$grep UNIX stud | cut –f 2, 3 |sort |tee file1
49) Shell scripting:
It is group of UNIX commands and shell keywords
The main concept of shell scripting is to handle text files
I) Boune shell----àsteave Bourne -----à$--------sh--- (sh as interpreter)
ii) Bash shell (borne again shell) ---same as above--àadvanced version of Bourne is BASH (Linux default shell)
iii) Korn shell------David korn----$----------ksh (interpreter) ----àused as AIX default shell
Mostly used shell is korn shell it supports re usability, all shell designed on bourn shell
50) $ksh            : shift to korn shell
51$echo $0              : it displays current child shell name
52) $alias                    : it lists all alias names
53) Unalias alias names: to delete alias names
54) $ history                 : it displays the previously executed commands
55) Echo                          : it display the string on screen (monitor)
File permissions:(xxx/xxx/xxx)
User/owner---permissions     (first part)
Group permissions                    (second part)
Other permissions                    (third part)
+--- (add permissions to u/g/o but it does not delete exiting permission)
--- (deny permissions)
=---- (assign permissions (add permissions to u/g/o but it  delete exiting permission))
rw-/rw-/r-- ---------àDefault permissions for regular files
rwx/rwx/r-x---------àdefault permission for directories
56) chmod              : it is used for to change file permissions
Syn: $chmod who/ [+/-/=]/
i) ls –l filename-------àrw- rw-   r—
ii) chmod g+x filename-----àrw- rwx  r—
iii) chmod u+x, g-w filename------àrwx r-x r—
iV) chmod g=w filename-----àrwx –w- r—
Octal code
Read------4
Write-----2
Execute—1
$chmod 756 filename-------àrwx r-x rw-
$chmod 642 filename----àrw- r--  -w-
57) chown        : to change owner name of the file
#chown owner name filename
58) chgrep    : to change group name of the file
# chgrp group name filename
58) $write    : it is user for to with the users but the user should be logged into the server
          $write techno2                   ii) $mesg n--àdeny the msg
          Hello                       iii) mesg y-àto allow msges
          Cmtl+d
59) awk/nawk file            : scan for patterns in a file and process the results
60) cat                            : concatenate (list) or file
61) chsh (paawd –e/-s) userlogin_shell: change the user login shell
62) df                              : report the summary of disk blocks and nodes free and in use
           i) df –k---àit displays the disk space in bytes
          ii) df –h---àit displays disk space in kilo bytes
           iii) df –g---àit displays the disk space in giga bytes
63)du  :it displays the directory wise disk usage in form of blocks each block size is 512 bytes
64)g zip                  :to create a zip file
Ex $gzip filename----ào/p: filename.gz
65) gunzip             : to unzip the files
Ex: gunzip filename.gz
66. compress         : it also used for to zip the file---àit used to save with .z format
67) Uncompress     : same as above
Gzip saves more memory than compress
68) zcat                 : it used to displays zip file contents in readable format
$zcat sample.gz

Or
$zcat sample.z
69) To kill foreground job cntl+c or cntl+z
$ sleep 500
Cntl+c
$ sleep 100&
70) ps or $ ps –f   : it displays current user account running process list (show status of active process)
71) $ps –a: it displays all user accounts running process list
72) Kill                           : it kill background process
Ex: kill PID
73) telnet           : to connect to remote server
74) ftp: file transfer protocol -----àtransfer files from one server to another
    $ ftp ipaddress
Login: -------
Password: ------
Ftp>ls  (server)
Ftp>|ls(client)
Ftp>get filename (to download a file)
Ftp>mget file1 file2----- (to download multi files)
Ftp>put filename (to upload a file)
Ftp>mput file1 file2----- (to upload multi files)
75)Ftp: to transfer files from one server user account to another server user account
   $su root --àto switch to admin
76) Wall                  : it is used for to sent broadcast message to all users who are currently working on server
$wall
Happy new-year
Cntl+d
77)mail         :it is used for to send the mail, if user is not logged in then also we can send mail
i) $ mail techno1
Cntl+d every user contains mailbox
at a time we can send msg to multiple users
2) $mail techno1 techno2 techno 3
Sub: from techno
Cntl+d
iii) $ mail techno<stud
stud send content as a mail to techno3
mail is the cmd to read mails in the mailbox
$mail
1>first mail
2>second mail reading
&2 it quickly opens second mail
&q--àquit from mail box
&w to save mail contents to a file
&pàprint mail contents
&r--àreplays
&d-àdelete mails
78) $mail –f:to read mails send to secondary mailbox
79) emacs    :full screen editor
80) echo       : echo the text string to on monitor
81) file         : classify the file type
82) expr       : evaluates the arguments, used to do arithmetic,etc in the shell
83) find         : find files, matching a type or pattern
84) Hostname         : display or set the name of the current machine
85) ln                           : link the source to target
86) lpq ,lpstat                   :show the status of the print jobs
87) lpr,lp                 :print to defind printer
88) lprm, cancel      : remove a print job from the print quee
89) man                 :display manual of given cmd
90) od                    :octal dump a binary file,in octal,ASCII,hex,decimal or char
91) passwd             :to set or change password
92) pr                    : filter the file and print it on the terminal
93) rcp hostname   : remotely copy files from this machine to another machine
94) rlogine hostname: login remotely to another machine
95) rsh hostname   : remote shell to run on another machine
96) script file                   : saves everything that appears on the screen to file until exit is executed
97) source file                  : read cmds from the file and execute them in the current shell
98) string file                                : used to search binary files for ASCII strings
99) Sty                                         : set or display terminal control options
100) uudecode file                     : decode a uuencoded file, recreating the original file
101) uuencode new name              : encode the binary file to 7-bit ASCII,usefull when sending via email, to be Decode as new name at destination
102) vi                               : visual ,full screen editor
103) jobs                : display background and suspended processes
104) kill %1            : remove suspended process #1
105) top                 : display the current, most computer-intensive commands
106) osview            : display the operating system statistics
107) setenv            : list environmental variables


VI EDITOR COMMANDS:


Vi editor is a default editor of all Unix Systems.It has several modes
In order to write Characters you will need to hit  to be in insert mode and then starting typing
1.       :w file name to write
2.       :w! will write and exit
3.       i-insert mode
4.       I-Inserts text at the cursor
5.       A-appends text at the end of the line
6.       a- appends text after cursor
7.       O-open a new line of text above the cursor
8.       o-open a new line of text below the cursor
9.       <escape> to invoke command mode from insert mode
10.   :!sh-to run unix commands
11.   X- to delete a single character
12.   dd-to delete an entire line
13.   ndd-to delete n number of lines
14.   d$-to delete from cursor to end of line
15.   yy-to copy a line to buffer
16.   P-to paste text from buffer
17.   nyy-copy n number of lines to buffer
18.   %s/string A/stringB/g-to replace StringA with StringB in Whole file
19.   G-to goto last line in file
20.   1G-to goto the first line
21.   w- to move forward to next word
22.   b-to move backward s to next word
23.   $-to  move the end of line
24.   J-join line with the one below it
25.   /string-to search string in file
26.   n-to search for next occurrence of string


      1.       e-end of word
2.       b-beginning of word
3.       ^-starting line
4.       $-end of line
5.       w- next word starting
6.       I-Starting of line-to write
7.       a-next char
8.       A-end of line
9.       o-next line
10.   O-Previous line
11.   X-delete
12.   dw-delete word
13.   u-undo
14.   3dw-3 words deleted
15.   dd- delete line
16.   yy- copy line
17.   p-paste
18.   3yy-3 lines copied
19.   .exrc-ex editor
20.   h-left
21.   j-down
22.   k-up
23.   l-right
24.   :wq-write & quite
25.   :w-Just written but not quite
26.   :q!-Quite without saving
27.   Set number(nu)
28.   Set nonu(nonumber)
29.   5h-5 position left
30.   20l-20 position right
31.   2j-2 lines down

UNIX questions and answers :


What is meant by passwd file?
This file maintains each and every user information with 7 fields. The 7 fields are Username: passwd: uid: gid: fullname: home: shell.
What is Shell?
Shell is a command line interpreter. Shell acts as an interface between user and the kernel.
What is Kernel?
Kernel is core part of  UNIX o/s. It is a group of hundreds of system calls.
What are different flavors of Unix o/s?
Any operating system designed based on unix kernel called as flavour of unix. The following are some flavours of unix
Linux ---- Red Hat
Sun solaris --- Sun Microsystem
IBM-AIX ----- IBM
Hp-ux ----- HP
Sco-unix ----- santa crus operations
IRIX------ Silicon Graphics.

What are the different security features in Unix?

          1. Password protection.
          2. File permissions.
          3. Encryption.

What’s the command to find out today’s date?
 date

What’s the command to find out users on the system?
 who

How do you find out the current directory you’re in?
pwd

What is the command to see the location of command?
Where is  <command name>
How do you find out your own username? 
Whoami    (or) log name

How to close the current user account?
Exit

How to create empty file?
Touch <filename>
How do you remove a file?
 Rm <filename>
How to join multifile files vertically?
Cat   file1 file2 file3 ……
The file for which we do not have write permission can be deleted using the command?
rm -f  <filename>
How do you remove a directory and its subdirectories?
 rm –rf <directoryname>
How to rename a file?
Mv <filename>
How to copy multiple files and directories into some other directory?
cp -r source_directory destination_directory
How to see hodden files?
Ls –a
How to see files and subdirectories files recursively?
Ls –R
How to see files in long list format page wise?
Ls –l | more
How to identify whether a file is normal file or directory? $ls -l filename/directoryname
if the first digit is - then it is file,
if it is d then it is directory file

What is the difference between "ls -r" and "ls -R"?

 ls -r lists the files in reverse alphabetical order... whereas ls -R lists the files and directories recursively

The difference between a soft link and a hard link?A symbolic (soft) linked file and the targeted file can be located on the same or different file system while for a hard link they must be located on the same file system.

what are the different commands used to create files?
1.touch - to create empty files (e.g) - touch <filename>
2.vi <filename>
3. cat>filename

List some wild card characters?
? -à Iit matches any single character
* -à It matches zero or more characters
[] -à It matches any single character in given list
. -à It matches any single character except enter key character
what is the output of the follwing command : ls [a-mno-r]*

list all the files in the current directory starting alphabet
is between a to m  or n or between o to r
How do you count words, lines and characters in a file?
 Wc <filename>
which command is used to identify the type of the file?
file
"grep" means
Globally search a regular expression and print it

How do you search for a string inside a given file?
 grep string filename
How do you search for a string inside a  current directory?
 grep string *

How do you search for a string in a directory with the subdirectories recursed?
 grep -r string *
Difference between grep, egrep and fgrep

grep : does not accept more then one expression

egrep : accepts more than one pattern for search. Also accepts patterns from a file.

fgrep : accepts multiple patterns both from command line and file but does not accept regular expressions only strings. It is faster than the other two and should be used when using fixed strings.

What are line patterns?
^ -à start of the line
$ -à End of the line

How to search empty lines in a given file?
Grep “^$” <filename>

How to count no of blank lines in a file?
Grep –c “^$” <filename>
How to remove Empty lines form a given file?
Grep –v “^$”  filename > temfilename
Mv  tempfilename  filename
What is pattern to search 4 digit word in a file?
Grep “\<[0-9] [0-9] [0-9] [0-9]\>” filename
What is pattern to search the line having only three characters?
Grep “^…$” filename
What is pattern to display lines ending with “$” character in a given file?
Grep “\$$” filename

How to display 2 and 4 th fileds from a given file if the delimetr is “:”?
Cut –d”:” –f  2,4 filename
How to display unique lines from a given file?
Sort –u filename
How to eliminate completely duplicate lines from a given file?
Uniq –u filename
How to remove all duplicate lines from a file?
Uniq –u filename > tempfilename
Mv  tempfilename  filename
How to delete “hello” word from a given file?
Sed “s/hello//” filename
awk Command
awk is a powful Unix command. It allows the user to manipulate files that are structured as columns of data and

Once you understand the basics of awk you will find that it is surprisingly useful. You can use it to automate things in ways you have never thought about. It can be used for data processing and for automating the application of Unix commands. It also has many spreadsheet-type functionalities.
There are two ways to run awk. A simple awk command can be run from the command line. More complex tasks should be written as awk programs ("scripts") to a file. Examples of each are provided below.
Example: % awk 'pattern {action}' input-file > output-file
meaning: take each line of the input file; if the line contains the pattern apply the action to the line and write the resulting line to the output-file.
If the pattern is omitted, the action is applied to all lines:

How to compare two files are same or not?
Cmp
How to display the first 10 lines from a file?
Head  -10  filename
Write a one line command to convert all the capital letters of a file "test" into lower case?
          cat filename | tr "[A-Z]"  "[a-z]"

The pipeline to list the five largest files in the current directory is

 ls -l | tr -s ' ' | sort -t ' ' -fnr +4 -5 | head –5

The pipeline to find out the number of times the character ? occurs in the file is
 tr -dc '?' < file | wc -c   ( Delete all the characters except ? and then make a word count.)

How to count total no. of users working in the system?
Who | wc –l

How to display the lines from 5 to 10 from a given file?
Head -10 filename | tail +5

what will be output of following command?
echo “Tecnosoft” | wc –c
9

What is the default umask?
022
What is the default permission for File & Directory ?
The Default privileges for file : 644
The default privileges for directory :  755
What UNIX command will control the default file permissions when files are created?Umask

Explain the read, write, and execute permissions on a UNIX directory.
Read allows you to see and list the directory contents.

Write allows you to create, edit and delete files and subdirectories in the directory.

Execute gives you the previous read/write permissions plus allows you to change into the directory and execute programs or shells from the directory.

What is chmod, chown and chgrp?
Chmod : It is used for to change permissions on files
Chown : It is used for to change ownership of a file
Chgrp : It is used for to change group of the file
If the owner doesn’t have write permission on a file, but his/her group has, can he/she edit it?
 No. He/she can't,because the owner's permission overrides the group's.
To see list of files and directories ,what permission required?
Read permission

What are PIDs?
They are process IDs given to processes. A PID can vary from 0 to 65535.

How do you list currently running process?
 ps

How do you stop a background process?
 kill pid
How do you find out about all running processes?
 ps -ag
How do you stop all the processes, except the shell window?
 kill 0
How do you fire a process in the background?
 ./process-name &
What does the command "kill -9 $! " do?
kills the last background process

if there is a process u want to run even after exiting the shell what is the
command used?
Nohup

 which command will get executed even after you log out?
 Nohup

which signal cannot be trapped?
kill –9

How to redirect standard error to a file? Answer2> filename

What does the top command display?
top command displays the current amount of memory occupied 
by the currently executing processes and the details. In addition to memory usage top command displays cpu usage and process details

What is the command to send message to all users who are logged in?
Wall

What is the command to send mail to other user?
Mail username
How to open secondary mail box?
Mail -f
What do you do if you don't want to be interrupted by other users' messages?
Ans. mesg n

Shell Scripting Interview questions

Difference between the output of echo ** and echo * *
echo ** lists all the filenames in the current directory..
echo * * lists all the filenames in the current directory twice.

The other way of running shell script apart from using sh command and chmod?
 ans:- using ! we can run a shell script

19. How do you refer to the arguments passed to a shell script? - $1, $2 and so on. $0 is your script name.
20. What’s the conditional statement in shell scripting? - if {condition} then … fi
21. How do you do number comparison in shell scripts? - -eq, -ne, -lt, -le, -gt, -ge
22. How do you test for file properties in shell scripts? - -s filename tells you if the file is not empty, -f filename tells you whether the argument is a file, and not a directory, -d filename tests if the argument is a directory, and not a file, -w filename tests for writeability, -r filename tests for readability, -x filename tests for executability
23. How do you do Boolean logic operators in shell scripting? - ! tests for logical not, -a tests for logical and, and -o tests for logical or.
24. How do you find out the number of arguments passed to the shell script? - $#
25. What’s a way to do multilevel if-else’s in shell scripting? - if {condition} then {statement} elif {condition} {statement} fi
26. How do you write a for loop in shell? - for {variable name} in {list} do {statement} done
27. How do you write a while loop in shell? - while {condition} do {statement} done
28. How does a case statement look in shell scripts? - case {variable} in {possible-value-1}) {statement};; {possible-value-2}) {statement};; esac
29. How do you read keyboard input in shell scripts? - read {variable-name}
30. How do you define a function in a shell script? - function-name() { #some code here return }
31. How does getopts command work? - The parameters to your script can be passed as -n 15 -x 20. Inside the script, you can iterate through the getopts array as while getopts n:x option, and the variable $option contains the value of the entered option.

Batch file:
Batch files allow MS-DOS and Microsoft Windows users to create a lists of commands to run in sequence once the batch file has been executed. For example, a batch file could be used to run frequently run commands, deleting a series of files, moving files, etc. A simple batch file does not require any special programming skills and can be done by users who have a basic understanding of MS-DOS commands

2 comments:

  1. Good one Sreedhar ....Feels like complete Unix under 1 umbrella ..Keep up teh good work , very helpful for a novice learner or reader of UNIX .

    ReplyDelete