Unix Basic Commands

Login Process:
login : user1
Password : 
# - System administrator promt
$ - User working promt
For instance, assume you entered correct userid and wrong password by mistake. It throws a message login incorrect. But Unix won't tell to user whether its login name incorrect or password incorrect.
Basic Commands:

$lognameIt displays the current user name
$pwdIt displays current/present working directory
$clearIt clears the screen
$exitTo logout from the screen
$dateIt displays system data and time
$who am IIt displays who you are
$whoIt displays the information about all the users who logged into system
$fingerIt displays the information about all the users who logged in
$calIt displays the current month calender
$cal yearIt displays the given year calender
$cal month yearIt displays the given month calender only
Run Levels:
#initTo change the system run levels
#init 0To shutdown the system
#init 1To bring the system to single user mode
#init 2To bring the system to multi user mode with no resource shared
#init 3To bring the system multi user mode with source shared
#init 6Halt and reboot the system to default run level
Creating Files:
There are two commands to create files: touch and cat
Syntax
1. $touch <filename>: It creates zero byte file size
Example: $touch sample
                The size of sample is zero bytes
Touch doesn't allow you to store anything in a file. It is used to create several empty files quickly
Example: $touch file1 file2 file3 file4
2. $cat <filename>
Example:
a) $cat > sample
____________       # To create a file sample and can store the content to the file
____________
____________
Ctrl + d (to close a file)
b) $cat >> sample
____________       # To append the data to the file
____________
____________
Ctrl + d
c) $cat file1 file2 file3 > file4
This would create a file for which contains the contents of file1 followed by file2 and followed by that of file3 i.e., it concatenates file1, file2 and file3 contents and redirects to file4. If file4 already contains something it would be over written
3. $cat < filename (or) $cat filename: To open a file
$cat sample
It displays sample file contents
$cat file1 file2 file3
It displays file1 contents followed by file2 then followed by file3
Removing files:
$rm command
To remove the given file
Syntax
$rm sample: It removes the sample file
$rm -i sample: It asks for confirmation before deleting the file
       $rm -i sample
       Remove sample? y - It removes
                                   n - It won't remove
$rm file1 file2 file3: It removes three files
$rm *: It removes all files in current directory
Creating Directory:
$mkdir command
To make directory
Syntax:
            $mkdir directory name
            $mkdir dir1
Creating multiple directories
            $mkdir dir1 dir2 dir3.... dir n
Changing Directory:
$cd dir1
$pwd
/usr/user1/dir1
$cd .. : To change into parent directory
$cd\   : To change to root directory
Removing directory:
$rmdir directory name: To delete a directory but directory should be emtpy
$rm -r directory name: It removes all files and sub directories, sub directory files including directory
Copying a file:
$cp file1 file2: This will copy the contents of file1 into file2. If file2 is already is exixted it overwrites
$cp -i file1 file2: If file2 is already existed then it asks for confirmation
          $cp -i sample1 sample2
          Overwrite sample2?
Renaming a file:
Syntax:
$mv <old file name> <new file name>
Moving of a file implies, removing it from current location and copying it to a new location
Creating a hidden files
Any file name which starts with (.) dot can be identified as hidden file
$cat >.sample
$mv emp .emp #to hide the file emp
$mv .emp emp #to unhide the file emp
File Compression:
Command to compress the files
1. Compress
Syntax: $compress filename
             The result of the above command is filename .Z.
$compress sample
On compression the original file is replaced by another which has the same name with .Z extension added to it
$compress -v sample
The option -v (verbose) option files compress to report how much space is saved. For example, in the above case it reported the following:
Sample: Compress: 76, 56% replaced with sample.Z
$Uncompress:
To get the compresses the back to its original state, we can use the uncompress utility as shown below.
$uncompress sample.Z
Sample.Z is deleted and original sample is recreated back in its original form and shape
Once file has been compressed, we cannot view it using the normal cat command. Unix provides a utility called Zcat for this purpose.
$zcat sample.Z
It displays file contents in readable format
2. Pack:
It is also able to compact a file. The compress offers a higher degree of compression as compared to pack
$pack sample
Sample 37.1% compression is smaller. The packed contents are stored in the file sample.Z and the original file sample is deleted. To view the contents of packed file we can us the pcat command
$unpack sample.Z
Unpack: sample: unpacked
3. gzip
Comparison of files:
$cmp file1 file2
It compares files1 file2. If both file contents are same number output if files are different then it displays line number and character location.
Difference of files
To compare the two text files, mostly we use diff command
File1
File2
aaa
bbb
bbb
c c
ccc
ddd
ddd
eee
eee
fff
fff
ggg
ggg
hhh

If there are no differences between the files, you will see no output, but if two text files are indeed different, all the text mismatches will be highlighted using the standard diff output:
$diff file1 file2
1d0
< aaa
3c2
< ccc
---
> ccc
7a7
> hhh
Lines like "1d0" and "3c2" are the coordinates and types of the differences between the two compared files, while line like "< aaa" and "> hhh" are the differences themselves.
Diff change notation includes 2 numbers and a character between them. Characters tells us what kind of change was discovered.
d - a line was deleted
c - a line was changed
a - a line was added
Number to the left of the character gives you the line number in the original (first) file, and the number to the right of the character tells you the line number in the second file used in comparison.
This means that 1 line was deleted. < aaa suggests that the aaa line is present only in the original file:
1d0
< aaa
And this means that the line number 3 has changed. You can see how this confirms that in the first file the line was "ccc" and in the second it now is "c c"
3c2
< ccc
---
>c c
Finally, this confirms that one new line appeared in the second file, it's "hhh" in the line number 7:
7a7
> hhh
Word count: It counts number of lines, word & character and displays
1. $wc file1
5          10          70          file1
In above output, 5 represents as total number of lines, 10 represents as total number of words, 70 represents as total number of characters.
2. wc file1 file2 file3
10
30
100
file1
5
15
65
file2
7
83
120
file3
22
128
285
total
3.
wc -l fileIt displays only line count
wc -w file1It displays only word count
wc -c file1It displays only character count
wc -l w file1It displays only line and word count
wc -wc file1It displays only word and character count
wc -lc file1It displays only line and character count
Listing of files:
1.
$lsIt displays list of files and directories
2.
$ls -xIt displays width wise
3.
$ls | pgIt displays list of files and directories pages wise
4.
$ls -x | pgIt displays list of files and directories page wise and wisth wise
5.
$ls -aIt displays list of files and directories including . and .. hidden files
6.
$ls -FIt displays files, directories, executable files, symbolic files

Example:$ls -F

i.) A1

ii) A2

iii) A3

iv) Sample\         /-----directory files

v) Letter*          *-----executable files

vi) notes@         @----link files
7.
$ls -rIt displays list of files and directories in reverse order i.e., descending order
8.
$ls -RIt displays list of files and directories recursively (whole structure)
9.
$ls -tIt displays list of files and directories based on data and time of creation i.e., last file to first file (recently created files)
10.
$ls -rtIt displays list of files and directories based on date and time of creation but in reverse order i.e., first to last file
11.
$ls -iIt displays files and directories along with inode numbers
12.
$ls -I
It displays list of files and directories in long list of format

File Type
Permission
Link
uname
Group
Size
Date
Filename
-
Rw-r--r--
1
user1
unix
560
Oct 21 1:30
sample
D
Rwxr-wr-w
2
user2
unix
 530
Nov 21 1:30
sample
Different types of Files:
-
Ordinary File
d
Directory File
b
Block special File
c
Character special File
l
Link File
Permissions:
Permissions for files:
There are three classes of file permissions for three classes of users: the owner (or user) of the file. The goup, the file belongs to, and all other users of the system
A set of nine characters denotes these permissions. Three types of permissions of a file are - 
Read
r
Write
w
Execute
x
$ls -l
-rwx-r-xr--
The first three letters of the permissions field refer to the owner's permissions; the second three to the members of the files group; and the last to any other users
The first letters, rwx, shows that the owner of the file can read it, write and execute it.
The second group of three characters r-x indicates that members of the group can read and execute the file but cannot write it, the last three characters, r-x, and show that all others can read execute the file but not write to it.
If you have read permission for a file, you can view its contents. Write permissions mean you can alter its contents. Execute permissions means that you can run the file as program
permissions for directories
For directories, read permission allows user to list the contents of the directory, write permissions allows users to create or remove files or directories inside that directory, and execute permissions allows users to change to this directory using the cd command or use it as part of path name.
Three types of users are: Users (u)
                                        Group (g)
                                        Others (o)
Note:- Two persons can change the permissions, Owner (user) and administrator
Changing File permissions
Chmod is the command to change file permissions or directory permissions.
Syntax:
$chmod [who][=/-/=][permissions] filename
First argument would be
u for user or owner
g for group
o for others
Second argument would be
+ for to add permissions
- for to remove permissions
= for to assign permissions (i., add specified permission and take away all other permissions, if present)
Third argument would be 
r to read
w to write
x to execute
Examples:
1. Add write permission to group members on sample file
$chmod g+w sample
2. Add execute permissions to others and owner on sample file
$chmod u+x, o+x sample
or
$chmod uo+x sample
3. Assign read permissions to others and removes write permissions from group members on sample file
$chmod o=r, g-w sample
Another form of the chmod command lets you set permissions directly, by using a numeric (octal) code to specify them. This code represents file's permissions by three octal digits; one for owner permissions, one for group permissions, and for others. These three digits appear together as one three digit number.
Permissions
Weight
Read4
Write2
Execute1
Read and Execute6
Write and Execute3
Read and Execute5
Read, Write and Execute7
Examples:
$chmod 700 sample
The above command sets read, write and execute permissions for the owner only and allows no one else to do anything with the sample file
$chmod 754 sample
The above command sets read, write and execute permissions for the owner and sets only read and execute to group and sets only read permissions to others on sample file
Using unmask to set permissions:
The chmod command allows you to alter permissions on a file by file basis and directory basis. The unmask command allows to do this this automatically when we create any file or directory. Everyone has default unmask setting set up either by system administrator or their profile.
Umask allows to specify the permissions of all files created after the umask command. Instead of dealing with individual file permissions, we can determine permissions for all future files with single command, unfortunately, using umask to specify permissions is rather complicated. The above two points to remember.
1. Umask uses a numeric code for representing absolute permissions just as chmod does. For example for a file 666 means read, write permissions for user, group and others. For a directory 777 means read, write and execute permissions for user, group and others.
2. We specify the permissions by telling umask what to substract from full permissions value depends on file (666) or directory (777).
$umask 022
The above command gives all the new files in this session will be given permissions as rw-r--r--. For new directories in this session will be given permissions as rwxr-xr-x
Changing the owner of a file
Every file has owner, usually the person who created it. When you create a file, you are its owner. The owner usually has broader permissions for manipulating the file than other users. Sometimes you need to change the owner of a file, for example, if you take over responsibilities for a file that previously belonged to another user.
The chown command takes two arguments the login name of the new user and name of the file.
Syntax
$chown user1 sample
In the above example, user1 is the new owner of the file sample.
Note: Only the owner of a file or the super user can use chown to change its ownership
Changing the group of file
 Every file belongs to a group, sometimes, such as when new groups are set up on a system or when files are copied to a new system, you may want to change the group to which a particular file belongs. This can be done using the chgrp command. The chgrp command takes two arguments, the name of the new group and name of the file.
Syntax$chgrp group1 sample
In above example, chgrp command changes sample file into group1 group.
Note: Only the owner of a file or the super user can use chgrp to change its ownership.
I/O Redirection operators
In all operating systems, there is a standard input device and a standard output device. In UNIX, as also in most other operating systems, the standard input device is keyboard and the standard output is the display screen
Special files that instruct all the programs to accept standard input from the keyword and direct the standard output to the display are provided by Unix. The three streams, i.e., standard input, standard output and standard error are denoted by number 0,1 and 2 respectively.
Stream
Device
Value
Standard inputKeyboard0
Standard outputTerminal screen1
Standard errorTerminal screen2
The specail characters specify from where the input is to be picked up and where the ouput is to be sent.
">"  -- Indicates output redirection operator
"<"  -- Indicates input redirection operator
$cat sample > outfile
The above command causes the output of the cat command of a file called outfile instead of standard output, the screen, where it would ordinally have gone
$cat < sample>>outfile
In case of input redirection, "<" is used to specify the standard input, which by default is the keyboard. The above command may also have been written as
$cat sample >> outfile
Finding Files:The find command helps you to locate files in the file system. With the find command, you can search through any part of the file system, looking for a file with particular name. It extremely powerful, and at times it can be a life saver, but also rather difficult to remember and to use.
An example of an common problem that find can help solve is locating a file that you have misplaced. For example, if you want to find a file called sample file but you can't remember where you put it, you can use find and search for it through all or part of the directory system.
The find command searches through the contents of one or more directories, including all their sub directories. You have to tell find in which directory to start its search.
Syntax:
$find <name of the directory to search> -name <filename> -print
Example:
$find . -name sample -print
/dir1/sample
The above command search in the current working directory denoted (.) for the file sample and print the path.
$find /usr/home -name sample -print
The above command search in the path under root for the file sample and print the path.
Running find in background
$find / -name sample -print > found_sample &
To run the command in the background, you end it with an ampersand (&). The above command a run find in the background to search the whole file system and sends its output to found_sample file. The advantage of running a command in the background is that you can go on to run other commands without waiting for the background job to finish.
Getting information about file types:
Sometimes you just want to know what kind of information of a file contains. For example, you may decide to put all your shell scripts together in one directory. You know that several scripts are scattered about several directories, but you don't know their names, or you aren't sure you remember all of them or you may want to print all of the text files in the current directory, whatever their content.
To know the type of file, file command reports the type of information contained in each of the files you give it. The following shows typical output from using file on all the files in current directory.
$file *
Examplesdirectory
SampleASCII text
link filesymbolic link
Helloexecutable file
$file hello.c
C program file
$file sample.cpp
C++ program file
Piping Concept:Quite often a single unix commands doesn't sufficient to solve a problem or to do a task. It can be done by joining commands together. The chief tool for this is redirection and pipe.
Redirection facility of unix let us connect commands to files.
Unix piping facility let us connect commands to other commands. It is possible to join commands by using a pipe ("|") i.e., to send the output of one command as input for the another.
For example
$who | wc -l
4
Pipe always take left side command output and redirects as input to right side of the command.
$ls | wc -l .total files
ls comand output is redirected as input to right side command wc -l and sends the output to a file called total files.
$ls | wc -l | tee total_files
Note: tee command will redirect the output to total files as well display the output on the console.
Wild card characters/Shell metacharacters
File submission type:
1.
*
It represents any combination of any number of characters. A null or no character at all may also qualify
2.
?
Stands for any one character
3.
[..]
Gives the shell a choice of any one character from the enclosed list
4.
[!..]
Gives the shell a choice of any character except those enclosed in the list
Here are few examples
$ls a*List all files beginning with character 'a'
$ls *sList all files beginning with any character and ends with 's'
$ls b*kList all files starting with 'b' and ends with 'k'
$ls ??List all files whose names are two characters long
$ls a?b?List all four character filenames, whose first character is 'a' and third character is 'b'
$ls [abcdefgh]*
(or)
$ls [a-h]*
Lists all files, first character should be from a to h
$ls [!a-h]Lists all files whose first character is anything other than an alphabet in the range a-h
Filter Commands:
grep command: Globally searches Regular Expression and Print it.
The grep command searches through one or more files for lines containing a target and then prints all of the matching lines. While performing patterns to be searched, we can use shell metacharacters.
For example:
$grep unix sample
Welcome to the world of unix os
$grep "unix os" sample
To search more than word, the string should be in double quotes
Using grep for queries
grep is often used to search for the information in structured files or simple databases. An example of such file is "students".
$cat students
101AjayCSrihitha Technologies
102VijayC++Srihitha Technologies
103RamUnixSrihitha Technologies
104RaviphpSrihitha Technologies
105hariVB6Srihitha Technologies
106samUnixSrihitha Technologies
Let us consider a simple personal database file. The file consists of records, each of which is terminated with new line. A record contains several field seperated by field seperator or delimiter. In this example delimiter is tab character. Database files like this can be created with an ordinary syste text editor like vi.
For example, using grep, find all students in the file that contain the word unix.
$grep unix students
103RamUnixSrihitha Technologies
106SamUnixSrihitha Technologies
$grep -i unix students (Ignores case sensitive)
103RamUnixSrihitha Technologies
106SamUnixSrihitha Technologies
$grep -c unix Students (Counts the lines that contain the word unix)
2
$grep -n unix Students (Prints along with line numbers
3103RamUnixSrihitha Technologies
6106SamUnixSrihitha Technologies
$grep -l unix Students (Lists all the file names that contain the word unix)
StudentssampleSrihithatest
$grep -v unix Students (It match other than the word unix or (not matches patern)
grep supports options with combination
$grep -ci
$grep -li
$grep -vn
$grep -vc
$grep -lc
$grep -vci

$cat >sample
The world is full of unix
Technology makes man software engineer
This is Unix world
Unix plays major role in real time
Ctrl+d
Three types of patterns to search the regular expressions:
1. Character Pattern (default)
Note: Create a file sample with content and practice the given examples
$grep "tecn*" sample
$grep "[aeiou]*" sample
$grep "b..d" sample
2. Word Pattern
Syntax: "\<word\>"
For example
$grep "\<the\>" sample                to print the exact word "the'
$grep "\<[0-9][0-9][0-9][0-9]\>" to print four digit number
$grep "\<...\>" sample                  exact four character word
3. Line Pattern
In the line patterns we have anchors.
1. ^ => Cap or caret                   # denotes beginning of the line
2. $ => dollar                             # denotes end of the line
Here are few examples for line patterns
$grep "^The" sample
It displays all the lines starting with in the file called sample
$grep "^\<The\>" sample
It displays all the lines starting with exact word called "The" in file called sample
$grep "r$" sample
It displays all the lines ending with character "e"
$grep "^$" sample
It displays all the empty lines
fgrep command:
The fgrep command is similar to grep, but with three main differences.
* You can use it to search for several targets at once
* It doesn't allow you to use regular expressions
* It is faster than grep, can be observed in case of large files or several small files
Searching for multiple targets:
Syntax:
$fgrep "Unix
>C
>php" students
The output looks like
101AjayCSrihitha Technologies
102RamUnixSrihitha Technologies
103RaviphpSrihitha Technologies
104SamUnixSrihitha Technologies
Note:
* Put the string in quotes.
* The fgrep doesn't accepts regular expressions, must be strings
* To give multiple search targets, each one must be on seperate line.
egrep command:
The egrep command is the most powerful member of the grep command family. You can use it like grep and fgrep. The egrep command accepts all of the basic regular expressions recognized by grep, as well supports multiple search targets
For example
$grep "C|C++|UNIX" students
101AjayCSrihitha Technologies
102VijayC++Srihitha Technologies
103RamUnixSrihitha Technologies
104SamUnixSrihitha Technologies
Sort command
It is also a filter; the sort command can be used for sorting the contents of a file. Apart from sorting file, the sort can merge multiple sorted files and store the result in the specified output file. While sorting the sort command bases it comparison on the first character in each line in the file. If the first character of two lines is same then second character in each line compared and so on. The sorting is done based on the ASCII collating sequence. Sorting can be done in two ways:
1. Sort by line:
Syntax$sort filename
For example
$sort sample
This would sort the contents of sample file and display the sorted output. By default it will sort in ascending order.
$sort -r sampleSort in descending order with -r option
$sort -u sampleIgnores duplicate lines
$sort -n sampleTo sort the data in integer format not ASCII format
2. Sort by field
Syntax
$sort
-f
+post1
-post2
filename
(Filed)
(Starting field)
(Ending field)

+post1 => including
-pos2   => excluding
For example take the file students
$cat students
0
1
2
3
101
Ajay
C
Srihitha Technologies
102
Vijay
C++
Srihitha Technologies
103
Ram
Unix
Srihitha Technologies
104
Ravi
php
Srihitha Technologies
105
hari
VB6
Srihitha Technologies
106
sam
Unix
Srihitha Technologies
Sort command automatically identifies the indexes
$sort -f +1 -2 students
It will sort according to the field 1 and displays the entire file as
101
Ajay
C
Srihitha Technologies
105
hari
VB6
Srihitha Technologies
103
Ram
Unix
Srihitha Technologies
104
Ravi
php
Srihitha Technologies
106
sam
Unix
Srihitha Technologies
102
Vijay
C++
Srihitha Technologies
$sort -t":" -f +1 -2 students
In the above students file delimiter is tab character. To specify the particular field seperator we use -t "delimiter"
Cut command:
It is also a filter, it cuts or pickup a given number of characters or fields from the specified file. For example, to see the large database of student's information but to view only selected fields, for instance id and course name should be displayed. Cut is the answer to get the desired output.
For example
$cut -f 1,3 students
101C
102C++
103Unix
104php
105VB6
106Unix
To specify the like: ; s , & * etc.,
$cut -d":" -f 2,3 students
Giving instruction to cut command that delimiter is ":"
Default delimiter is tab character.
Uniq command:
It also filter, the command uniq displays uniq lines in a file, provided the file should be in sorted order i.e., uniq command works only with sorted files.
For example
$cat >test
Aaa
Bbb
Ccc
Ddd
Aaa
Ccc
Hhh
$uniq test
Aaa
Bbb
Ccc
Ddd
Hhh
$uniq -u test           it displayed non duplicated lines
Bbb
Ddd
Hhh
$uniq -d test           it displays only duplicated lines
Aaa
Ccc
Editor
Three editors are available in almost all versions of Unix. There are:
1. ed editor
The ed editor is basically a line editor, which means that ed assigns line numbers to lines in a file, every time you do something, you must tell ed which line or lines to do it.
2. ex editor
An improved version of ed, understands all the commands of ed it is shade better in user friendliness with more informative error messages.
3. vi editor
Compared to ed or ex the vi text editor is head and shoulders above them in almost every way. It is a screen editor rather than a line editor; it shows you as much of the file as it can fit on the screen. Vi is case sensitive Vi is available on almost all Unix systems. 

Modes of operation:
The vi program has three modes of operation:
1. Command mode:
This is the default mode. In this mode all the keys pressed by these are interpreted to be editor commands.
2. Insert mode:
This mode permits insertion of new text, editing of existing text or replacement of existing text.
3. The ex command mode:
This mode permits us to give commands at the command line. The bottom line of the vi screen is called the command line. Vi uses the command line to display messages and commands. All commands entered in the ex command mode are displayed in the command line. This mode is so called because commands given in this mode are compatible with the commands of the ex editor.
Changing of modes in Vi
From command to insert mode 
I, i, o, O, r, R, s, S, a, A
Press insert mode to command mode
Press Esc key
From command mode ex mode 
* Be sure you are in command mode 
* Press shift ":" to enter ex mode
Command
Operation
i
insert before cursor position
I
insert at the beginning of line
a
insert after cursor position
A
insert at the end of the current line
o
open a new line below
O
open a new line above
S
Deletes the current line and comes to insert mode
s
deletes current character and shift to insert mode
R
Replace from the current cursor till end of line
r
Replaces a single character
Positioning by character
hMoves the cursor one character to the left
back spaceMoves the cursor one character to the left
lMoves the cursor one character to the right
space barMoves the cursor one character to the right
Positioning by line
j
Moves the cursor down one line from its present position in the same column
k
Moves the cursor up one line from its present position in the same column
+
Moves the cursor down to the beginning of next line
-
Moves the cursor up to the beginning of next line
Enter key
Moves the cursor up to the beginning of next line
Positioning by word
w
Moves the cursor to the right, to the first char of the next word
b
Moves the cursor to the back, to the first char of the next word
e
Moves the cursor to the end of the current word
Cursor movement in command mode
Ctrl f
move one screen full down
Ctrl b
move one screen full up
Ctrl d
move a half screen full down
Ctrl u
move a half screen full up
Command
operation
Positioning in the window
H
Moves the cursor to the first line on the screen i.e., “home”
M
Moves the cursor to the middle line on the screen
L
Moves the cursor to the last line on the screen
Commands for deleting the text
(n)x
Deletes the character at the current cursor position
X
Deletes the character to the left of cursor position
(n)dw
Deletes the word from cursor to the next space or next punctuation
(n)dd
Deletes the current line
d0
Deletes the current line from the cursor to the beginning of the line
d$
Deletes the current line from the cursor to the end of the line
Command for copying and paste text
yy
yanks line from cursor position
yw
word
y0
from cursor to beginning
y$
from cursor to ending
p
Paste the yanked buffer
Command for quitting vi
: w [file]
Save and continue
: q [file]
Stop without saving
: w! [file]
Same as : w but override check
: q! [file]
Same as : q but override check
: set nu
Setting the line numbers for a file
: set nonu
removing the line numbers

No comments:

Post a Comment