MCA Linux OS Commands Lab Manual
MCA Linux OS Commands Lab Manual
Lab Manual
Lab-1,2
A shell is a program that provides the command line (i.e., the all-text
display user interface) on Linux and other Unix-like operating systems.
It also executes (i.e., runs) commands that are typed into it and displays
the results. bash is the default shell on Linux.
1. Echo command
echo is a built-in command in the bash and C shells that writes its
arguments to standard output.
The items in square brackets are optional. A string is any finite sequence
of characters (i.e., letters, numerals, symbols and punctuation marks).
1
‘\n’ newline
‘\\’ backslash
When used without any options or strings, echo returns a blank line
on the display screen followed by the command prompt on the
subsequent line. This is because pressing the ENTER key is a
signal to the system to start a new line, and thus echo repeats this
signal.
When one or more strings are provided as arguments, echo by
default repeats those stings on the screen. Thus, for example,
typing in the following and pressing the ENTER key would cause
echo to repeat the phrase This is a pen. on the screen:
echo This is a pen.
For example, a variable named x can be created and its value set to 5
with the following command:
x=5
2
Echo is particularly useful for showing the values of
environmental variables, which tell the shell how to behave as a
user works at the command line or in scripts (short programs).
The -n option can be used to stop echo from adding the newline to
output.
3
Echo command is also used to evaluate the expression
X=11
Y=2
Echo `expr $x + $y`
13
4
Display message welcome on screen
echo 'Welcome'
Write message File deleted to a file called /tmp/log.txt
2. Date
Linux “date” command returns you the date and time when you call it
without any options. Use the date command to display the current date
and time or set the system date / time over ssh session. You can also run
the date command from X terminal as root user.
This is useful if the Linux server time and/or date is wrong, and you
need to set it to new values from the shell prompt.
# date
Sun Dec 14 11:33:55 IST 2008
This is the simplest use of this command. Now suppose you wanted to
just get the date and nothing more:
5
# date +”%d”
14
If you want the date, complete with date, month, and year:
# date +”%d%m%y”
141208
To get the day of the week along with the rest of the date:
# date +”%a%d%m%y”
Sun141208
These are a few of the many possibilities that the “date” command offers
you. Check out “date –help for options”. Some interesting ones are:
%D date (mm/dd/yy)
%d day of month (01..31)
%m month (01..12)
%y last two digits of year (00..99)
%a locale’s abbreviated weekday name (Sun..Sat)
%A locale’s full weekday name, variable length (Sunday..Saturday)
%b locale’s abbreviated month name (Jan..Dec)
%B locale’s full month name, variable length (January..December)
%H hour (00..23)
%I hour (01..12)
%Y year (1970…)
You can also do some fancy formatting. If you want to add a hyphen or
a back-slash in between the different parts of the date:
# date +”%d-%m-%Y”
14-12-2008
# date +”%d/%m/%Y”
14/12/2008
You can also use spaces and commas. Here’s a pretty fancy example:
6
# date +”%A,%B %d %Y”
Sunday,December 14 2008
DATE: 02/08/01
TIME:16:44:55
For example, set new data to 2 Oct 2006 18:00:00, type the following
command as root user:
# date -s "2 OCT 2006 18:00:00"
OR
# date --set="2 OCT 2006 18:00:00"
7
date -s "11/20/2003 12:48:00"
3. Hostname
Hostname is the program that is used to either set or display the current
host, domain or node name of the system. These names are used by
many of the networking programs to identify the machine.
With no arguments, hostname prints the name of the current host system.
With one argument, it sets the current host name to the specified string.
You must have appropriate privileges to set the host name. Synopsis:
hostname [name]
The only options are --help and --version. An exit status of zero
indicates success, and a nonzero value indicates failure
8
4. Arch
The arch command will print the type of computer you are using.
5. Uname
6. Uptime
7. Whoami
whoami prints the user name associated with the current effective user
ID.
Example:
9
8. who
Syntax
Examples
10
Files and Directories Commands Pwd, cd, cd .., cd /, mkdir, rmdir, cat
Directory commands
Display name of current directory (pwd) List the Contents of a directory (ls)
Switch to another directory (cd) Create/Delete directories (mkdir, rmdir, rm
-r)
File commands
Pwd is the basic command that can be useful to find out where you are in the linux system ( your current
directory path), this simple example the step to use Linux pwd command on the bash shell command
prompt to print current working directory on Linux system.
Command Description:
The Linux 'pwd' (Print the current working directory) command is used to display the directory
that you are currently in or your working directory. The command >pwd is used to display the
full path name of the current directory.
Command type:
11
2. cd
3. ls
-l long listing
-R list current directory and all other directories within current directory
list in column format and append '*' to executable files, '@' to symbolic
-CF
linked files, '/' to directories
12
-t list more recent accessed files first
list files in the '/etc/ directory, only starting with 'rc' and sort results by
ls -lt /etc/rc*
most recent
13
4. mkdir ,rmdir and rm –r
14
mkdir mydirectory Will create a new directory named 'mydirectory'
Lab-3,4
File Management commands
1. Wildcards (*, ?, [ ]
[from-to ] Values entered within square brackets represent a range (from-to) for a
single character
15
*z all files where the last character is a 'z'
a*m all files that start with the letter 'a' and end with 'm'
th?? all files that start with 'th' and are only four characters long
all files that start with the letter 'x' and the second character contains 'A, B or
x[A-C]*
C'
[!M-O]* all files except those that start with 'M, N or O'
Example: cp oldfile myfile - Will copy the existing file 'oldfile' to a new file 'myfile'
16
4. Delete files (rm)
rm - Delete files
rm -i abc* prompt to remove each file in current directory starting with 'abc'
rm abc* remove all files in current directory starting with 'abc' automatically
rm -rf
By default, rm will not remove non-empty directories. However rm accepts several options that will
allow you to remove any directory. The rm -rf statement is famous because it will erase anything
(providing that you have the permissions to do so). When you are logged on as root, be very careful
with rm -rf (the f means force and the r means recursive) since being root implies that permissions
don't apply to you, so you can literally erase your entire file system by accident.
17
The command wc is used to count lines, words or characters in a file or piped results from
another command.
-c Number of characters
-w Number of words
-l
wc /etc/sendmail.cf Lists the number of lines, words and characters in the file
'sendmail.cf'
ls /etc | wc -l Lists the number of files and directories in the directory 'etc'
Files can consist of several types. The command file is used to display a description for the
type.
Example: file a* will list all files in the current directory that start with the letter "a" and
provide a description for the file type.
The command cat is a multi-purpose utility and is mostly used with TEXT files.
Create a new file and optionally allow the manual entry of contents
o cat >[filename]
o Example: cat >myfile will create a file named myfile and allow you to enter contents.
o Press Control-D to exit entry mode.
o WARNING: If "myfile" already existed, this command would replace the old file with
the contents of the new file.
Combine text files
o cat file1 file2 >newfile - This will combine file1 and file2 into newfile.
18
Dissplay the contents of a file --cat myfile
Delete the contents of a file --cat /dev/null >myfile
8. Touch commands
Touch command is used to create a file .It can change file access and modification time. It is also
used to change the timestamps (i.e., dates and times of the most recent access and modification)
on existing files and directories.
touch's syntax is
When used without any options, touch creates new files for any file names that are provided as
arguments (i.e., input data) if files with such names do not already exist. Touch can create any
number of files simultaneously.
Thus, for example, the following command would create three new, empty files named file1,
file2 and file3:
A nice feature of touch is that, in contrast to some commands such as cp (which is used to copy
files and directories) and mv (which is used to move or rename files and directories), it does not
19
automatically overwrite (i.e., erase the contents of) existing files with the same name. Rather, it
merely changes the last access times for such files to the current time.
touch's options
Syntax
-a Change the access time of file. Do not change the modification time unless -m is
also specified.
-c Do not create a specified file if it does not exist. Do not write any diagnostic
messages concerning this condition.
-m Change the modification time of file. Do not change the access time unless -a is
also specified.
Examples
the -a option changes only the access time, while the -m option changes only the
modification time. The use of both of these options together changes both the access and
modification times to the current time, for example:
9. Paste command
NAME
20
sort (sort lines of text files)
syntax:
sort [options] [file...]
DESCRIPTION
sort sorts, merges, or compares all the lines from the given files, or the standard input if no files
are given. The sort command sorts a file according to fields--the individual pieces of data on
each line. By default, sort assumes that the fields are just words separated by blanks, but you can
specify an alternative field delimiter if you want (such as commas or colons). Output from sort is
printed to the screen, unless you redirect it to a file.
OPTIONS
-f
Fold lower case characters into the equivalent upper case characters when sorting so that, for
EXAMPLE, 'b' is sorted the same way 'B' is.
-r
Reverse the result of comparison, so that lines with greater key values appear earlier in the
output instead of later.
-t separator
Use character separator as the field separator when finding the sort keys in each line. By default,
fields are separated by the empty string between a non-whitespace character and a whitespace
character.
EXAMPLE
% sort -f name_list.txt
arranges the lines in file name_list.txt according to the ascii character table. The option -f tells
sort to ignore the upper and lower character case.
If you had a file like the one shown here containing information on people who contributed to
your presidential reelection campaign, for example, you might want to sort it by last name,
donation amount, or location. (Using a text editor, enter those three lines into a file and save it
with donor.data as the file name.)
Let's take this sample donors file and sort it. The following shows the command to sort the file
on the second field (last name) and the output from the command:
sort +1 -2 donors.data
Jack Arta 250000 Indonesia
21
Bay Ching 500000 China
Cruella Lumper 725000 Malaysia
Let's look at a few more examples with the sample company.data file shown here,
To sort the file on the third field (serial number) in reverse order and save the results in
sorted.data, use this command:
22
Consider a situation where the fields are separated by colons instead of spaces. In this case,
we will use the -t: flag to tell the sort command how to find the fields on each line. Let's start
with this file:
Itorre, Jan:406378:Sales
Nasium, Jim:031762:Marketing
Ancholie, Mel:636496:Research
Jucacion, Ed:396082:Sales
To sort the file on the second field (serial number), use this command:
The cut command takes a vertical slice of a file, printing only the specified columns or fields.
Like the sort command, the cut command defines a field as a word set off by blanks, unless you
specify your own delimiter.
It's easiest to think of a column as just the nth character on each line. In other words, "column 5"
consists of the fifth character of each line.
-c list The list following -c specifies character positions (for instance, -c1-72
would pass the first 72 characters of each line).
-f list The list following -f is a list of fields assumed to be separated in the file by
a delimiter character
-d delim The character following -d is the field delimiter (-f option only). Default is
tab. Space or other characters with special meaning to the shell must be
quoted. delim can be a multi-byte character
file A path name of an input file. If no file operands are specified, or if a file
operand is -, the standard input will be used.
Consider a slight variation on the company.data file we've been playing with in this section:
406378:Sales:Itorre:Jan
031762:Marketing:Nasium:Jim
636496:Research:Ancholie:Mel
396082:Sales:Jucacion:Ed
If you want to print just columns 1 to 6 of each line (the employee serial numbers), use the -
c1-6 flag, as in this command:
If you want to print just columns 4 and 8 of each line (the first letter of the department and
the fourth digit of the serial number), use the -c4,8 flag, as in this command:
to print just the last names by specifying the -d: and -f3 flags, like this:
406378:Sales:Itorre:Jan
031762:Marketing:Nasium:Jim
636496:Research:Ancholie:Mel
396082:Sales:Jucacion:Ed
To use a space as the delimiter put the delimiter in single quotes, like this: -d' '
24
To cut from a starting point to the end of the line, just leave off the final field number,
To assign the output to a variable and display the value of the variable
The head command displays the first few lines at the top of a file. It can be useful when you
want a quick peek at a large file, as an alternative to opening the file with a text editor. By
default, head will show the first ten lines of a file, but you can also tell it how many lines to
display.
25
---------------------------------------------------------------------------------------------------------------------
Like head, it can save you time, because it's a lot quicker than calling up a file with a text editor
and scrolling all the way down to the bottom. By default, tail will show the last ten lines of a file,
Syntax
-n number Equivalent to -c number, except the starting location in the file is measured in
lines instead of bytes. The origin for counting is 1; that is, -n+1 represents the
first line of the file, -n-1 the last.
file Name of the file you wish to display
Examples
tail myfile.txt
The above example would list the last 10 (default) lines of the file myfile.txt.
26
tail myfile.txt -n 2
The above example would list the last 100 lines in the file myfile.txt.
X`x x
Syntax
finger [username]
27
Examples
$ finger linux
Exercise
Who am i
Q2. Count the number of words, sentences and characters in the directory.
wc
Q3. To list the directories and sub directories by specifying their locations
Ls -l
Q4. To list the total time that the system has been setup
uptime
Q5.Display the directory contents of your directory. The output should be multi column and should
contain the hidden files.
Ls –R
28
Q6. Create and verify a new file using the cat command. Also display its contents
cat >newfile
cat newfile
Rmdir
pwd
cd /etc
3. Now change to your home directory using only three key presses.
cd /
ls
ls -l
ls /etc
29
10. Stay where you are, and list the contents of /bin and /sbin.
ls /bin /sbin
ls ~
12. List all the files (including hidden files) in your home directory.
ls -al ~
ls -lh /boot
mkdir ~/testdir
15. Change to the /etc directory, stay here and create a directory newdir in your home
directory.
mkdir -p ~/dir1/dir2/dir3
rmdir testdir
Lab 5,6
14. Chmod
30
u, g, o or all Whose permission you are changing:
user, group, other or all
chmod go+rw file1 file2 add read and write access for
group and others for files 'file1'
and 'file2'
Permissions
Each security group has 3 flags that control the access status
To view the permissions, you use the ls -l command. For each file or
directory listed, you will see the permissions, owner and group name,
and file or directory name.
About chmod
Syntax
32
Permissions
u - User who owns the file.
g - Group that owns the file.
o - Other.
a - All.
r - Read the file.
w - Write or edit the file.
x - Execute or run the file as a program.
Numeric Permissions:
CHMOD can also to attributed by using Numeric Permissions:
Examples
This gives the file read/write by the owner and only read by everyone
else (-rw-r--r--).
33
This would be the following 400+040+004+200+100+010+001 = 755
where you are giving all the rights except the capability for anyone to
write to the file.cgi file(-rwxr-xr-x).
Examples
Lab-7
How to: Change / Setup bash custom prompt (PS1)
Prompt is control via a special shell variable. You need to set PS1 variable. If set, the value is
executed as a command prior to issuing each primary prompt.
PS1 - The value of this parameter is expanded (see PROMPTING below) and used as the
primary prompt string. The default value is \s-\v\$ .
\\u@\h \\W]\\$
Modifying the prompt is easy task. Just assign a new value to PS1 and hit enter key:
My old prompt --> [vivek@105r2 ~]$
PS1="hello : "
Output: My new prompt
hello :
So when executing interactively, bash displays the primary prompt PS1 when it is ready to read a
command. Bash allows these prompt strings to be customized by inserting a number of
backslash-escaped special characters that are decoded as follows:
Let us try to set the prompt so that it can display today’d date and hostname:
PS1="\d \h $ "
Output:
To add colors to the shell prompt use the following export command syntax:
'\e[x;ym $PS1 \e[m'
Where,
37
To set a red color prompt, type the command:
$ export PS1="\e[0;31m[\u@\h \W]\$ \e[m "
Cyan 0;36
clear command
Clear the screen.
Lab-8
38
grep command
grep searches the input files for lines containing a match to a given pattern list. When it finds a
match in a line, it copies the line to standard output (by default), or whatever other sort of output
you have requested with options.
By default, grep prints the matching lines. Use grep to search for lines of text that match one or
many regular expressions, and outputs only the matching lines.
DESCRIPTION
Grep searches the named input FILEs (or standard input if no files are named, or the file name -
is given) for lines containing a match to the given PATTERN. By default, grep prints the
matching lines.
3. –n to precede each line of output with the number of the line in the text file from which it
was obtained:
$ grep -n 'word' /path/to/file
Some examples:
39
6. displays the line numbers containing this search string.
7. checks which users are not using bash, but accounts with the nologin shell are not displayed.
Lab-9
Process managing commands
ps command
40
Syntax ps [-options]
ps
Typing ps alone would list the current running processes. Below is an example of the output that
would be generated by the ps command.
ps -f
41
kill command
Cancels a job.
Syntax
kill pid
DESCRIPTION
top provides an ongoing look at processor activity in real time. It displays a listing of the most
CPU-intensive tasks on the system, and can provide an interactive interface for manipulating
processes. It can sort the tasks by CPU usage, memory usage and runtime.
Command: last
Last -show listing of last logged in users
SYNOPSIS
last
42
Last searches back through the file /var/log/wtmp (or the file designated by the -f flag) and
displays a list of all users logged in (and out) since that file was created.
Lab-10
If you use it with no arguments you will the usage of all files, directories and subdirectories
(recursively) of the working directory.
43
Options
-a write counts for all files, not just directories
The first line would be the default last line of the 'du' output indicating the total size of the
directory and another line displaying the same size, followed by the string 'total'.
44
-h Shows the in human readable format, so with K, M, G suffix near the size
So the sizes of the files / directories are this time suffixed with a 'k' if its kilobytes and 'M' if
its Megabytes and 'G' if its Gigabytes.
Really a useful tool when you are running out of disk space, and need to know which directory
or files are using that space.
Examples
$ du neha
The above command would give you the directory size of the directory neha
$ du -ah
This command would display in its output, not only the directories but also all the files that
are present in the current directory. Note that 'du' always counts all files and directories
while giving the final size in the last line. But the '-a' displays the filenames along with the
directory names in the output. '-h' is once again human readable format.
45
$ du -s
This displays a summary of the directory size. It is the simplest way to know the total size
of the current directory.
$ du -S
This would display the size of the current directory excluding the size of the subdirectories
that exist within that directory. So it basically shows you the total size of all the files that
exist in the current directory.
------------------------------------------------------------------------------------------------------
to find the free disk space you could use ' df '. shows disk usage for all your mounted
filesystems in 1K blocks
Syntax
df [OPTION]... [FILE]...
$ df
Typing the above, outputs a table consisting of 6 columns. All the columns are very easy to
understand. Remember that the 'Size', 'Used' and 'Avail' columns use kilobytes as the unit.
The 'Use%' column shows the usage as a percentage which is also very useful.
$ df -h
Displays the same output as the previous command but the '-h' indicates human readable
format. Hence instead of kilobytes as the unit the output would have 'M' for Megabytes and
'G' for Gigabytes.
46
Example :
I have my Linux installed on /dev/hda1 and I have mounted my Windows partitions as well
(by default every time Linux boots). So 'df' by default shows me the disk usage of my Linux
as well as Windows partitions. And I am only interested in the disk usage of the Linux
partitions. This is what I use :
45%
Basically this command makes 'df' display the disk usages of all the partitions and then
extracts the lines with /dev/hda1 since I am only interested in that. Then it cuts the
characters from the 41st to the 43rd column since they are the columns that display the
usage in % , which is what I want.
--------------------------------------------------------------------------------------------------
The Linux “free” command gives information about total used and available space of physical
memory and swap memory with buffers used by kernel in Linux/Unix like operating systems.
This article provides some useful examples of “free” commands with options, that might be
useful for you to better utilize memory that you have.
Free command used to check the used and available space of physical memory and swap
memory in KB. See the command in action below.
# free
47
total used free shared buffers cached
Free command with option -b, display the size of memory in Bytes.
# free -b
Free command with option -k, display the size of memory in (KB) Kilobytes.
# free -k
48
total used free shared buffers cached
To see the size of the memory in (MB) Megabytes use option as -m.
# free -m
Using -g option with free command, would display the size of the memory in GB(Gigabytes).
# free -g
Mem: 0 0 0 0 0 0
-/+ buffers/cache: 0 0
49
Swap: 3 0 3
Free command with -t option, will list the total line at the end.
# free -t
By default the free command display “buffer adjusted” line, to disable this line use option as -o.
# free -o
50
8. Display Memory Status for Regular Intervals
The -s option with number, used to update free command at regular intervals. For example, the
below command will update free command every 5 seconds.
# free -s 5
The -l switch displays detailed high and low memory size statistics.
# free -l
51
10. Check Free Version
# free -V
52