Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
116 views

MCA Linux OS Commands Lab Manual

The document provides information about various Linux commands related to shells, directories, files and system information. It discusses the echo, date, hostname, arch, uname, uptime, whoami and who commands in detail including their syntax and examples of using each command. It also lists some common directory and file management commands like pwd, cd, ls, mkdir, rmdir, cp, mv, rm, wc and cat.

Uploaded by

Abhishek Raj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

MCA Linux OS Commands Lab Manual

The document provides information about various Linux commands related to shells, directories, files and system information. It discusses the echo, date, hostname, arch, uname, uptime, whoami and who commands in detail including their syntax and examples of using each command. It also lists some common directory and file management commands like pwd, cd, ls, mkdir, rmdir, cp, mv, rm, wc and cat.

Uploaded by

Abhishek Raj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

OS with Linux

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.

A command is an instruction telling a computer to do something. An


argument is input data for a command. Standard output is the display
screen by default, but it can be redirected to a file, printer, etc.

Basic Commands-1 Commands- echo, date, hostname, arch,


username, uptime, whoami, who

1. Echo command

echo is a built-in command in the bash and C shells that writes its
arguments to standard output.

The syntax for echo is


echo [option(s)] [string(s)]

The items in square brackets are optional. A string is any finite sequence
of characters (i.e., letters, numerals, symbols and punctuation marks).

The program accepts the following options. Options must precede


operands, and the normally-special argument ‘--’ has no special
meaning and is treated like any other string.

‘-n’ Do not output the trailing newline.

‘-e’ Enable interpretation of the following backslash-escaped


characters in each string:

1
‘\n’ newline

‘\t’ horizontal tab

‘\v’ vertical tab

‘\\’ backslash

Examples of echo command

 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.

It is not necessary to surround the strings with quotes, as it does


not affect what is written on the screen. If quotes (either single or
double) are used, they are not repeated on the screen.

 it can also show the value of a particular variable if the name of


the variable is preceded directly (i.e., with no intervening spaces)
by the dollar character ($), which tells the shell to substitute the
value of the variable for its name.

For example, a variable named x can be created and its value set to 5
with the following command:
x=5

The value of x can subsequently be recalled by the following:


echo The number is $x.

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).

For example, to see the value of HOME, the environmental value


that shows the current user's home directory, the following would
be used:
echo $HOME

 Likewise, echo can be used to show a user's PATH environmental


variable, which contains a colon-separated list of the directories
that the system searches to find the executable program
corresponding to a command issued by the user:
echo $PATH

 echo, by default, follows any output with a newline character.


This is a non-printing (i.e., invisible) character that represents the
end of one line of text and the start of the next. It is represented by
\n in Unix-like operating systems. The result is that the subsequent
command prompt begins on a new line rather than on the same
line as the output returned by echo.
 The -e option is used to enable echo's interpretation of additional
instances of the newline character as well as the interpretation of
other special characters, such as a horizontal tab, which is
represented by \t. Thus, for example, the following would produce
a formatted output:
echo -e "\n Projects: \n\n\tplan \n\tcode
\n\ttest\n"

(The above command should be written on a single line, although


it may render as two lines on smaller display screens.)

 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

echo 'File has been deleted' > /tmp/log.txt


Append message File deleted to a file called /tmp/log.txt

echo 'File has been deleted' >> /tmp/log.txt


Append message and command output on screen

echo "Today's date is $(date)"


Append message and command output to a file

echo "Today's date is $(date)" > /tmp/date.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.

You must login as root user to use date command.

The first thing to do is to get the current date and time:

# 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 '+DATE: %m/%d/%y%nTIME:%H:%M:%S'

Would list the time and date in the below format.

DATE: 02/08/01
TIME:16:44:55

Linux Set Date

Use the following syntax to set new data and time:

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"

You can also simplify format using following syntax:


# date +%Y%m%d -s "20081128"

7
date -s "11/20/2003 12:48:00"

Set the date to the date and time shown.

Linux Set Time

To set time use the following syntax:


# date +%T -s "10:13:13"

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.

hostname: Print or set system name

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

Command to get architecture type (print machine architecture)

The arch command will print the type of computer you are using.

5. Uname

Print name of current system.

6. Uptime

uptime - Tell how long the system has been running.

uptime gives a one line display of the following information. The


current time, how long the system has been running, how many users are
currently logged on, and the system load averages for the past 1, 5, and
15 minutes.

7. Whoami

whoami prints the user name associated with the current effective user
ID.

Example:

9
8. who

Displays who is on the system.

Syntax

who [-H] [-m] [am i] [ file ]

-H Output column headings above the regular output.

-m Output only information about the current terminal.

-u List only those users who are currently logged in.

am i In the "C" locale, limit the output to describing the


invoking user, equivalent to the -m option. The am and i
or I must be separate arguments.

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

1. Wildcards (*, ?, [ ]  Count the number of lines, words or


2. Copy files (cp) characters (wc)
3. Rename files (mv)  Display file type (file)
4. Delete files (rm)  Concatenate files (cat)

Directory management commands

1. pwd - Display name of current directory

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:

Bourne Shell :Builtins command.

[root@linux fedora]# type pwd

pwd is a shell builtin

11
2. cd

Switch to another directory

To switch to another directory, the command cd is used.

Examples What it does

cd Will place you in your home directory

cd / Will move you to the root directory

cd /etc Will move you to the /etc directory

cd ../ Will move you back one directory

3. ls

List the Contents of a directory

The command ls is used to list the contents of a directory.

Options What it does

-l long listing

-R list current directory and all other directories within current directory

-a list hidden files

list in column format and append '*' to executable files, '@' to symbolic
-CF
linked files, '/' to directories

-r list in reverse alphabetically order

12
-t list more recent accessed files first

filename(s) Values to match

Examples What it does

ls only list file/directory names in current directory

ls -l list all file/directory information in current directory(long version)

ls -R list all files in current directories and below

ls -lt list all files, sorted by most recent accessed 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

mkdir and rmdir - Create/Delete directories

The command mkdir is used to create a new directory.

The command rmdir or rm -r is used to delete a directory or directories

Examples What it does

14
mkdir mydirectory Will create a new directory named 'mydirectory'

rmdir existingdirectory Will delete the existing directory named 'existingdirectory'

rm -r existingdirectories Will delete the existing directory named 'existingdirectories' and


all directories and files below it.

Lab-3,4
File Management commands

1. Wildcards (*, ?, [ ]

Wildcard characters are used to help find file or directory names

Options What it does

* asterisk symbol is used to represent anycharacter(s)

? question mark is used to represent any single character

[from-to ] Values entered within square brackets represent a range (from-to) for a
single character

[!from-to ] Values entered within square brackets represent a range (from-to) to


exclude for a single character

Examples What it does

a* all files starting with the letter 'a'

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

[a-c]* all files that start with 'a, b or c'

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'

2. Copy files (cp) Copy files

To copy a file, the command cp is used

Example: cp oldfile myfile - Will copy the existing file 'oldfile' to a new file 'myfile'

3. Rename files (mv)Rename files

The command mv is used to rename a file

Example: mv myfile yourfile - Will rename the file 'myfile' to 'yourfile'

16
4. Delete files (rm)

rm - Delete files

Examples What it does

rm myfile remove the file 'myfile'

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.

5. Count the number of lines, words or characters (wc)

wc - Count the number of lines or characters

17
The command wc is used to count lines, words or characters in a file or piped results from
another command.

Options What it does

-c Number of characters

-w Number of words

-l

filename file name(s) to use

Examples What it does

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'

6. Display file type (file)

- Display Type-of-File Description

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.

7. Concatenate files (cat)

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

touch [option] file_name(s)

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:

touch file1 file2 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:

touch -am file3

9. Paste command

Merge corresponding or subsequent lines of files.

paste file1 file2

10. Sort and Cut commands

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.)

Bay Ching 500000 China


Jack Arta 250000 Indonesia
Cruella Lumper 725000 Malaysia

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

Specify the sort keys like this:

+m Start at the first character of the m+1th field.


-n End at the last character of the nth field (if -N omitted, assume the end of the line).

Let's look at a few more examples with the sample company.data file shown here,

Jan Itorre 406378 Sales


Jim Nasium 031762 Marketing
Mel Ancholie 636496 Research
Ed Jucacion 396082 Sales

 To sort the file on the third field (serial number) in reverse order and save the results in
sorted.data, use this command:

sort -r +2 -3 company.data > sorted.data


Mel Ancholie 636496 Research
Jan Itorre 406378 Sales
Ed Jucacion 396082 Sales
Jim Nasium 031762 Marketing

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:

sort -t: +1 -2 company.data


Nasium, Jim:031762:Marketing
Jucacion, Ed:396082:Sales
Itorre, Jan:406378:Sales
Ancholie, Mel:636496:Research

11. Cut 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:

cut -c1-6 company.data


406378
23
031762
636496
396082

 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:

cut -c4,8 company.data


3S
7M
4R
0S

 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

cut -d: -f3 company.data


Itorre
Nasium
Ancholie
Jucacion

 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,

$ who am i | cut –f- -d' '

 To assign the output to a variable and display the value of the variable

$name=`who am i | cut –f- -d' '`


$ echo $name

12. Heads or Tails

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.

head [-number | -n number] filename

-number The number of the lines you want to display.


-n number The number of the lines you want to display.
filename The file that you want to display the x amount of lines of.

Here are a couple of examples:

head file1 Show first ten lines of file1.

head -5 file1 Show first five lines of file1.

25
---------------------------------------------------------------------------------------------------------------------

The tail Command

The tail command displays the last few lines of a file.

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,

tail some.file Show last ten lines of s ome.file.


tail -3 some.file Show last three lines of some.file.

Syntax

tail [ number | -n number] [file]

-number count by lines

-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.

Combining head and tail


head and tail can be combined to create a combo, let say I wanna print a file from line 6 to line
10, I can do this:

head -n10 foo.txt | tail -n5

X`x x

Syntax

spell myfile.txt spell checks the file myfile.txt.

13. Finger Command

Lists information about the user.

finger [username]
27
Examples

$ finger linux

Exercise

Q1.Display the name of the client machine with complete details

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

Q7. Delete file(s) and directory(s)

Rmdir

working with directories

1. Display your current directory.

pwd

2. Change to the /etc directory.

cd /etc

3. Now change to your home directory using only three key presses.

cd (and the enter key)

4. Change to the /boot/grub directory using only eleven key presses.

cd /boot/grub (use the tab key)

5. Go to the parent directory of the current directory.

cd .. (with space between cd and ..)

6. Go to the root directory.

cd /

7. List the contents of the root directory.

ls

8. List a long listing of the root directory.

ls -l

9. Stay where you are, and list the contents of /etc.

ls /etc
29
10. Stay where you are, and list the contents of /bin and /sbin.

ls /bin /sbin

11. Stay where you are, and list the contents of ~.

ls ~

12. List all the files (including hidden files) in your home directory.

ls -al ~

13. List the files in /boot in a human readable format.

ls -lh /boot

14. Create a directory testdir in your home directory.

mkdir ~/testdir

15. Change to the /etc directory, stay here and create a directory newdir in your home

directory.

cd /etc ; mkdir ~/newdir

16. Create in one command the directories ~/dir1/dir2/dir3 (dir3 is a subdirectory

from dir2, and dir2 is a subdirectory from dir1 ).

mkdir -p ~/dir1/dir2/dir3

17. Remove the directory testdir.

rmdir testdir

Lab 5,6
14. Chmod

Permission Commands chmod commands with options: u-


r,u+rw,o-r, o+x,g-x,o-r,o+x,g-x.

Chmod commands : octals no 777

Options What it does

30
u, g, o or all Whose permission you are changing:
user, group, other or all

+ or>- Type of change: add permission or


subtract permission

combination of r , w which permission you are changing: read,


or x write or execute

file or directory name of file or directory to change

Examples What it does

chmod go-w thisfile remove write access for group


and others for the file 'thisfile'

chmod go+rw file1 file2 add read and write access for
group and others for files 'file1'
and 'file2'

chmod ugo+rwx file1 add read, write and execute for


everyone for 'file1'.

Permissions

Each file or directory has 3 security groups...

 Owner (Each file or directory has a specific owner or creator)


 Group Access (Each file or directory is assigned to a specific
group)
 All Others (If a user is not the owner or is not assigned to the
group, they are considered in the other category)

Each security group has 3 flags that control the access status

 Flag 1 = read (4)


 Flag 2 = write (2)
31
 Flag 3 = execute (1) (pertains to shell scripts or execute programs
only)

They are listed as 'rwx' or a "-" if the access is turned off.

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.

Examples What it means

- read, write and executable for owner, group


rwxrwxrwx and all others

-rwxrwx--- read, write and executable for owner, group


only

-rwx------ read, write and executable for owner only

-rw-rw-rw read and write for owner, group and all


others

-rwxr-xr-x read, write and executable by owner, only


read and executable by group and others

-rw-r--r- read and write by owner, read only for


group and all others

About chmod

Changes the permission of a file.

Syntax

chmod [OPTION]... MODE[,MODE]... FILE...

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:

400 read by owner


040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody

Examples

The above numeric permissions can be added to set a certain permission,


for example, a common HTML file on a Unix server to be only viewed
over the Internet would be:

chmod 644 file.htm

This gives the file read/write by the owner and only read by everyone
else (-rw-r--r--).

Files such as scripts that need to be executed need more permissions.


Below is another example of a common permission given to scripts.

chmod 755 file.cgi

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).

chmod 666 file.txt

Finally, another common CHMOD permission is 666, as shown below,


which is read and write by everyone.

Examples

SNo Command Description

chmod u+x Gives the user execute permission on


myfile myfile.
chmod u+x Gives the user execute permission on
myfile myfile.
chmod +x myfile Gives everyone execute permission on
myfile.
chmod ugo+x Same as the above command, but
myfile specifically specifies user, group and
other.
chmod 400 Gives the user read permission, and
myfile removes all other permission. These
permissions are specified in octal, the first
char is for the user, second for the group
and the third is for other. The high bit (4)
is for read access, the middle bit (2) os for
write access, and the low bit (1) is for
execute access.
chmod 764 Gives user full access, group read and
myfile write access, and other read access.
chmod 751 Gives user full access, group read and
myfile execute permission, and other, execute
34
permission.
chmod +s myfile Set the setuid bit.
chmod go=rx Remove read and execute permissions for
myfile the group and other.
chmod u-r Removes the user read permission on
myfile myfile
chmod u+rw Gives the user read and write permission
myfile on myfile
chmod o-r Removes the other user read permission
myfile on myfile
chmod o+x Gives other user execute permission on
myfile myfile.
chmod g-x Removes the group execute permission
myfile on myfile
chmod u+x Gives user execute permission on myfile
myfile
chmod go- w remove write access for group and others
thisfile for the file 'thisfile'
chmod go+rw add read and write access for group and
file1 file2 others for files 'file1' and 'file2'
chmod ugo+rwx add read, write and execute for everyone
file1 for 'file1'.
chmod 777 file1 Gives user, group,other full access
chmod 644 file1 Gives the user read ,write permission,
group read permission, and other, read
permission.
chmod 755 file1 Gives the user full access, group read and
execute permission, and other, read and
execute permission.
chmod 000 file1 removes all permissions
chmod 700 file1 Gives the user full access and removes all
other permissions.
chmod 711 file1 Gives the user full access and group and
other, execute permission
chmod 555 file1 Gives read and execute permission to all.
35
chmod 111 file1 Gives execute permission to all
chmod 544 file1 Given a file with permissions 755, change
to r-x-r--r--

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\$ .

How do I display current prompt setting?

Simply use echo command, enter:


$ echo $PS1
Output:

\\u@\h \\W]\\$

How do I modify or change the prompt?

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:

 \a : an ASCII bell character (07)


36
 \d : the date in "Weekday Month Date" format (e.g., "Tue May 26")
 \e : an ASCII escape character (033)
 \h : the hostname up to the first '.'
 \H : the hostname
 \s : the name of the shell, the basename of $0 (the portion following the final slash)
 \t : the current time in 24-hour HH:MM:SS format
 \T : the current time in 12-hour HH:MM:SS format
 \@ : the current time in 12-hour am/pm format
 \A : the current time in 24-hour HH:MM format
 \u : the username of the current user
 \v : the version of bash (e.g., 2.00)
 \w : the current working directory, with $HOME abbreviated with a tilde

Let us try to set the prompt so that it can display today’d date and hostname:
PS1="\d \h $ "
Output:

Sat Jun 02 server $

Now setup prompt to display date/time, hostname and current directory:


$ PS1="[\d \t \u@\h:\w ] $ "
Output:

[Sat Jun 02 14:24:12 vivek@server:~ ] $

Add colors to the prompt

To add colors to the shell prompt use the following export command syntax:
'\e[x;ym $PS1 \e[m'

Where,

 \e[ Start color scheme


 x;y Color pair to use (x;y)
 $PS1 is your shell prompt
 \e[m Stop color scheme

37
To set a red color prompt, type the command:
$ export PS1="\e[0;31m[\u@\h \W]\$ \e[m "

List of Color code


Color Code Color Code

Black 0;30 Red 0;31

Blue 0;34 Purple 0;35

Green 0;32 Brown 0;33

Cyan 0;36

Replace digit 0 with 1 to get light color version.

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.

grep command syntax

grep 'word' filename


grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'

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.

1. –w - Use grep to search words only


When you search for boo, grep will match fooboo, boo123, etc. You can force grep to select
only those lines containing matches that form whole words i.e. match only boo word:

$ grep -w "boo" /path/to/file

2. –c Count line when words has been matched


grep can report the number of times that the pattern has been matched for each file using -c
(count) option:
$ grep -c 'word' /path/to/file

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

4. –v Grep invert match


You can use -v option to print inverts the match; that is, it matches only those lines that do
not contain the given word. For example print all line that do not contain the word bar:
$ grep -v bar /path/to/file

Some examples:

5. displays the lines from /etc/passwd containing the string root.

cathy ~> grep root /etc/passwd


root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

39
6. displays the line numbers containing this search string.

cathy ~> grep -n root /etc/passwd


1:root:x:0:0:root:/root:/bin/bash
12:operator:x:11:0:operator:/root:/sbin/nologin

7. checks which users are not using bash, but accounts with the nologin shell are not displayed.

cathy ~> grep -v bash /etc/passwd | grep -v nologin

8. counts the number of accounts that have /bin/false as the shell.

cathy ~> grep -c false /etc/passwd


7

Lab-9
Process managing commands
ps command

Reports the process status.

40
Syntax ps [-options]

-a List information about all processes most frequently requested


-A List information for all processes.

-f Generate a full listing.

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.

PID TTY TIME CMD


6874 pts/9 0:00 ksh
6877 pts/9 0:01 csh
418 pts/9 0:00 csh

ps -f

Display full information about each of the processes currently running.

UID PID PPID C STIME TTY TIME CMD


hope 29197 18961 0 Sep27 ? 00:00:06 sshd: hope@pts/87
hope 32097 29197 0 Sep27 pts/87 00:00:00 -csh
hope 7209 32097 0 12:17 pts/87 00:00:00 ps -ef

41
kill command
Cancels a job.

Syntax

kill pid

pid A decimal integer specifying a process or process group to be signaled

If process number 0 is specified, all processes in the process group are


signaled. If the first pid operand is negative, it should be preceded by -- to
keep it from being interpreted as an option.

Command: top display top CPU processes


top [options]

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

Memory Management Commands

Disk Usage Commands


du - Linux command line for displaying the disk usage information
du command is used to know how much space a file or directory is using on your disk. The
command to find the directory size is ' du '. This command prints the disk usage (in Kb) of
each directory and it's sub directories. By default it starts from the current directory, but
supplying the name of a directory after the command will make it start from that directory. This
command prints the disk usage (in Kb) of each directory. The last line of the output gives you
the total size of the current directory including its subdirectories.

du [options] [file or dir]

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

-c Displays the grand total at the end

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.

-s Sumarize, to know the total size of the current directory.

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.

$ du -ch | grep total


This would have only one line in its output that displays the total size of the current
directory including all the subdirectories.

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.

------------------------------------------------------------------------------------------------------

df command- Display free disk space

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]...

-a include dummy file systems


-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)

Examples 'df' - finding the disk free space / disk usage

$ 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 :

$ df -h | grep /dev/hda1 | cut -c 41-43

This command displays the following on my machine

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.

1. Display System Memory

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

Mem: 1021628 912548 109080 0 120368 655548

-/+ buffers/cache: 136632 884996

Swap: 4194296 0 4194296

2. Display Memory in Bytes

Free command with option -b, display the size of memory in Bytes.

# free -b

total used free shared buffers cached

Mem: 1046147072 934420480 111726592 0 123256832 671281152

-/+ buffers/cache: 139882496 906264576

Swap: 4294959104 0 4294959104

3. Display Memory in Kilo Bytes

Free command with option -k, display the size of memory in (KB) Kilobytes.

# free -k

48
total used free shared buffers cached

Mem: 1021628 912520 109108 0 120368 655548

-/+ buffers/cache: 136604 885024

Swap: 4194296 0 4194296

4. Display Memory in Megabytes

To see the size of the memory in (MB) Megabytes use option as -m.

# free -m

total used free shared buffers cached

Mem: 997 891 106 0 117 640

-/+ buffers/cache: 133 864

Swap: 4095 0 4095

5. Display Memory in Gigabytes

Using -g option with free command, would display the size of the memory in GB(Gigabytes).

# free -g

total used free shared buffers cached

Mem: 0 0 0 0 0 0

-/+ buffers/cache: 0 0

49
Swap: 3 0 3

6. Display Total Line

Free command with -t option, will list the total line at the end.

# free -t

total used free shared buffers cached

Mem: 1021628 912520 109108 0 120368 655548

-/+ buffers/cache: 136604 885024

Swap: 4194296 0 4194296

Total: 5215924 912520 4303404

7. Disable Display of Buffer Adjusted Line

By default the free command display “buffer adjusted” line, to disable this line use option as -o.

# free -o

total used free shared buffers cached

Mem: 1021628 912520 109108 0 120368 655548

Swap: 4194296 0 4194296

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

total used free shared buffers cached

Mem: 1021628 912368 109260 0 120368 655548

-/+ buffers/cache: 136452 885176

Swap: 4194296 0 4194296

9. Show Low and High Memory Statistics

The -l switch displays detailed high and low memory size statistics.

# free -l

total used free shared buffers cached

Mem: 1021628 912368 109260 0 120368 655548

Low: 890036 789064 100972

High: 131592 123304 8288

-/+ buffers/cache: 136452 885176

Swap: 4194296 0 4194296

51
10. Check Free Version

The -V option, display free command version information.

# free -V

procps version 3.2.8

52

You might also like