0% found this document useful (0 votes)
142 views66 pages

LINUX MODULE-1 - New

The document provides an overview of the Linux operating system architecture. It discusses that the core of Linux is the kernel, which manages system resources and interacts with hardware. The kernel includes subsystems like process scheduling, memory management, virtual file systems, networking and inter-process communication. System calls provide an interface between user processes and the kernel. Linux also includes shell programs, system utilities and application programs that users interact with through the shell or graphical user interface.

Uploaded by

Fausiya Salim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views66 pages

LINUX MODULE-1 - New

The document provides an overview of the Linux operating system architecture. It discusses that the core of Linux is the kernel, which manages system resources and interacts with hardware. The kernel includes subsystems like process scheduling, memory management, virtual file systems, networking and inter-process communication. System calls provide an interface between user processes and the kernel. Linux also includes shell programs, system utilities and application programs that users interact with through the shell or graphical user interface.

Uploaded by

Fausiya Salim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Introduction to Linux

Prepared By: Alby Joseph

Operating system

An operating system is a program that acts as an intermediary between a user of a computer and
the computer hardware.

Operating system goals:

 Execute user programs and make solving user problems 


 Make the computer system convenient to use. 
 Use the computer hardware in an efficient manner.
Computer System Components 

  Hardware – provides basic computing resources (CPU, memory, I/O devices). 
 Operating system – controls and coordinates the use of the hardware among the various
 application programs for the various users. 
 Applications programs – define the ways in which the system resources are used to
solve the computing problems of the users (compilers, database systems, video games,
 business programs). 
 Users (people, machines, other computers). 

Operating-System Structures:

Process Management, Memory Management, File Management, I/O System Management,


Networking

Major operating system components:

Kernel, Device drivers, Shell, Utility programs, Graphical user interface (GUI)

 The operating system kernel is in direct control of the underlying hardware. The kernel
provides low-level device, memory and processor management functions .Basic
hardware-independent kernel services are exposed to higher-level programs through a
library of system calls.
 Application programs and system utility programs make use of system calls.
Applications and system utilities are launched using a shell or a graphical user
interface that provides direct user interaction

Questions
1.What do you mean by an operationg system?
LINUX HISTORY

Prepared By:Alex V. G

All modern operating systems have their roots in 1969 when Dennis Ritchie and Ken
Thompson developed the C language and the Unix operating system at AT&T Bell Labs. They
shared their source code (yes, there was open source back in the Seventies) with the rest of the
world, including the hippies in Berkeley California. By1975, when AT&T started selling Unix
commercially, about half of the source codewas written by others. The hippies were not happy
that a commercial company sold software that they had written; the resulting (legal) battle ended
in there being twoversions of Unix in the Seventies : the official AT&T Unix, and the free BSD
Unix.In the Eighties many companies started developing their own Unix: IBM created AIX, Sun
SunOS (later Solaris), HP HP-UX and about a dozen other companies didthe same. The result
was a mess of Unix dialects and a dozen different ways to do thesame thing. And here is the first
real root of Linux, when Richard Stallman aimed to end this era of Unix separation and
everybody re-inventing the wheel by starting
the GNU project (GNU is Not Unix). His goal was to make an operating system that was freely
available to everyone, and where everyone could work together (like in the Seventies). Many of
the command line tools that you use today on Linux or Solaris are GNU tools.
The Nineties started with Linus Torvalds, a Swedish speaking Finnish student, buying a 386
computer and writing a brand new POSIX compliant kernel. He put the source code online,
thinking it would never support anything but 386 hardware. Many people embraced the
combination of this kernel with the GNU tools, and the rest, as they say, is history. Today more
than 90 percent of supercomputers (including the complete top 10), more than half of all
smartphones, many millions of desktop computers, around 70 percent of all web servers, a large
chunk of tablet computers, and several appliances (dvdplayers, washing machines, dsl modems,
routers, ...) run Linux. It is by far the most commonly used operating system in the world.

Characteristics of Linux
 Linux is multiuser . 
  Linux is multitasking . 
 UNIX/Linux is command-line oriented .
Linux
 Usage 
Desktop computers –
Windows 90%, Linux 2% 

•Servers 
–Windows 36.3%, Linux 12.7% 
•Supercomputers 
–Windows
 1.4%, Linux 85% 
•Mobile, PDA,
Headsets –Linux 16.7% 

GNU/ Linux‘s Advantages


Stability
–It is very rarely to see the Kernel Panic
Free Software
–The is not any charge for software
Support Wide Range of
Hardware-Linux is portable to any
hardware platform:
Security
–Open source à There is not any backdoor
–Quick bug fixing
Linux is scalable:

QUESTIONS
 Explain the history of linux. 
 Define the characteristics linux. 

LINUX ARCHITECTURE
Prepared By: Aleyamma Sebastian

Different Types Of Architectures In Linux


The GNU/Linux operating system consists of a kernel, a shell, utilities, and application
programs. The architecture of the Linux operating system is displayed below:
Fig: Components of the Linux OS.
SHELL UTILITIES APPLICATION PROGRAMS

KERNEL

HARDWARE

Kernel
The core of the Linux system is the kernel, which is also the operating system program.
The kernel controls the resources of a computer, allocating them to different users and tasks. It
interacts directly with the hardware, making programs easy to write and portable across different
hardware platforms. However, the user does not interact directly with a kernel.
It act as an interface between operating system and other hardware resources. It is the
main part of the operating system that loads firsts and remains in the main memory. It is the
bridge between the application and the actual data processing to support the application.
The Linux kernel is composed of five main subsystems:

1. Process Scheduler (SCHED) is responsible for controlling process access to the CPU.
The scheduler enforces a policy that ensures that processes will have fair access to the CPU,
while ensuring that necessary hardware actions are performed by the kernel on time.

2. Memory Manager (MM) permits multiple processes to securely share the machine's main
memory system. In addition, the memory manager supports virtual memory that allows Linux to
support processes that use more memory than is available in the system. Unused memory is
swapped out to persistent storage using the file system then swapped back in when it is needed.

3. Virtual File System (VFS) abstracts the details of the variety of hardware devices by
presenting a common file interface to all devices. In addition, the VFS supports several file
system formats that are compatible with other operating systems.
4. Network Interface (NET) provides access to several networking standards and a variety of
network hardware.
5. Inter-Process Communication (IPC) subsystem supports several mechanisms for process-
to-process communication on a single Linux system.
System Call
The User Space and Kernel Space are in different spaces. When a System Call is
executed, the arguments to the call are passed from User Space to Kernel Space. A user process
becomes a kernel process when it executes a system call. System call is an interface between a
process and the operating system.

eg. A user has requested to MS paint. This request will be sent to the operating system,
and then the operating system will generate some activity to support MS paint and run on the
system.

System calls are of different types:-

File Management System call – For performing open, close, read, write etc operations.
Process Control System Call – For performing Load,execute,create etc operations.
Device Management System Call – For performing request device,write device,release
device etc operations.
Communication System call – For performing Send message,transfer status etc
operations etc.
Linux Utilities and Application Programs
Linux utilities or commands are a collection of programs that service processing
requirements. These programs can be started by using the shell.
DBMS, Word processors etc.
Hardware Platform
The resource of the system such as keyboard, monitor, printer etc with which user can
input/output the request
Shell
Linux has a single user interface called the shell. The shell provides services for a user.
A user interacts with the computer by using the shell. Some of the common shells in Linux are
bash, sh, tcsh, csh, and ksh. An operating system shell is divided into two parts:-
 Command line:- It is the part of the operating system which receives and executes
 the operating system command by the user. 
 GUI(Graphical User Interface):- This provides a user friendly environment.
such as the KDE and GNOME window managers. 
Shells Available In Linux
The description of the various shells available for UNIX/Linux given below.
 Bourne Shell - The Bourne shell was developed at AT&T and named after its
developer Stephen R. Bourne. The Bourne shell is distributed with all UNIX systems
and is stored in the /bin directory. The executable file name for Bourne shell is ‗sh‘. It
is one the most widely used shells for UNIX systems.
 C Shell – The C shell was developed by William Joy at the University of California
at Berkeley to provide a programming interface similar to the C programming
 language.The executable file name for the C shell is ‗csh‘. 
 Korn shell – The Korn shell was developed at AT&T and named after its developer
 David Korn. The Korn shell combines the features of both the Bourne and C shell. 
The executable files name for the Korn shell is ‗ksh‘. 
  Bash Shell –(Bourne Again shell) Bash is a product of Free Software Foundation‘s 
GNU project. The Bash shell is the default shell for most Linux systems and is stored
in the /bin directory. In Red Hat Linux, the ‗sh‘ command is a symbolic link to
‗bash‘. 
Other Shells
 Restricted Shell – The restricted shell is used to provide limited access on the
operating system to a user. The restricted shell to restrict the users of the operating
system to a limited environment.
  Tcsh Shell – Tcsh stands for Tom‘s C shell and is an enhancement of the C shell. The 
Tcsh shell is also known as the TC shell. We can execute the Tcsh shell by typing
 either ‗csh‘ or ‗tcsh‘ at the command prompt. 
 A Shell – The A shell was developed by Kenneth Almquist of the university of
Berkeley. It emulates the Bourne shell. The A shell is suitable for computers that have
 limited memory. The executable file name for the A shell is ‗ash‘. 
 Z Shell – The Z shell offers the features of Tcsh and Korn shells. In addition, it
provides a large number of utilities and extensive documentation. The executable file
name for the Z shell is ‗zsh‘. 
Model Questions
1. Explain the architecture of Linux OS. [9 Mark] (Punjab University, MG University)
2. Explain any 5 types of shells available in Linux. (Punjab University)
3. What are different types of shells? [9 Mark] (MG University)
4. What is Kernel and Shell?
5. Explain different system calls ?
Linux Unix
Linux is an example of Open Source Unix is an operating system that is
software development and Free very popular in universities,
What is it?: Operating System (OS). companies, big enterprises etc.

Linux can be freely Different flavors of Unix have


distributed,downloaded freely, different cost structures according
Cost: distributed through magazines, to vendors
Books etc. There are priced versions
for Linux also, but they are normally
cheaper than Windows.

Everyone. From home users to Unix operating systems were


developers and computer enthusiasts developed mainly for
alike. mainframes,servers and
User: workstations except OSX, Which is
designed for everyone. The Unix
environment and the client-server
program model were essential
elements in the development of the
Internet
Linux kernel is developed by the Three bigest distributions are
Manufacturer: community. Linux Torvalds oversees Solaris (Oracle), AIX (IBM) & HP-
things. UX Hewlett Packard. And Apple
Makes OSX, an unix based os..

Price: Free but support is available for a Some free for development use
price. (Solaris) but support is available
for a price.

Processors: Dozens of different kinds. x86/x64, Sparc, Power, Itanium,


PA-RISC, PowerPC and many
others.

Development and Linux is developed by Open Source Unix systems are divided into
Distribution: development i.e. through sharing and various other flavors, mostly
collaboration of code and features developed by AT&T as well as
through forums etc and it is various commercial vendors and
distributed by various vendors. non-profit organizations.
Architectures: Originally developed for Intel's x86 is available on PA-RISC and
hardware, ports available for over Itanium machines. Solaris also
two dozen CPU types including available for x86/x64 based
ARM systems.OSX is PowerPC(10.0-
10.5)/x86(10.4)/x64(10.5-10.8)
GUI: Linux typically provides two GUIs, Initially Unix was a command
KDE and Gnome. But Linux GUI is based OS, but later a GUI was
optional. created called Common Desktop
Environment. Most distributions
now ship with Gnome.
File system Ext2, Ext3, Ext4, Jfs, ReiserFS, Xfs, jfs, gpfs, hfs, hfs+, ufs, xfs, zfs
support: Btrfs, FAT, FAT32, NTFS format
Text mode BASH (Bourne Again SHell) is the Originally the Bourne Shell. Now
interface: Linux default shell. It can support it's compatible with many others
multiple command interpreters. including BASH, Korn & C.

Security: Linux has had about 60-100 viruses A rough estimate of UNIX viruses
listed till date. None of them actively is between 85 -120 viruses reported
spreading nowadays. till date.

Threat detection In case of Linux, threat detection and Because of the proprietary nature
and solution: solution is very fast, as Linux is of the original Unix, users have to
mainly community driven and wait for a while, to get the proper
whenever any Linux user posts any bug fixing patch. But these are not
kind of threat, several developers as common.
start working on it from different
parts of the world
Inception: Inspired by MINIX (a Unix-like In 1969, it was developed by a
system) and eventually after adding group of AT&T employees at Bell
many features of GUI, Drivers etc, Labs and Dennis Ritchie. It was
Linus Torvalds developed the written in ―C‖ language and was
framework of the OS that became designed to be a portable, multi-
LINUX in 1992. The LINUX kernel tasking and multi-user system in a
was released on 17th September, time-sharing configuration.
1991

FEATURES AND FACILITIES OF LINUX


Prepared by: Anit Maria George
Multiprogramming
Linux allows several programs to be executed simultaneously by different users.This feature is
called multiprogramming.
Time-Sharing
Multiprogramming is possible on the Linux due to the concept of time sharing.In time sharing
the operating system has to manage various programs simultaneously. Programs are queued, and
CPU time is shared among programs.
Multitasking
A program in Linux is broken down into tasks.,An OS to handle the execution of multiple tasks
is known as multitaskin.When a task is waiting for the completion of another task, the CPU
instead of wasting time start to execute the next task.The kernel is responsible for scheduling
tasks.
Virtual Memory
The amount of physical memory might not always be sufficient to execute large applications or
enable multiple applications to be active at a given time Such situations , a partition that is a
logical portion of the hard disk can be utilized as virtual memory.The OS places data and
programs, which are not frequently used, in this portion of the hard disk and loads them in the
memory whenever It is a process that runs on the operating system and enablesresources that
havebeen published form of Webpages .A web server can enable users to access resoures on a
wide area network.A Web server is commonly referred to as a computer that delivers Web pages
sabma
The name samba derived from the Server Message Block(SMB).
SMB is the protocol used by Microsoft operating systems to sharefiles and printers Samba is a
suite of programs that implement the SMB protocol on Linux.Using Sanba, you can share a
Linux file system with Windows 95, Windows 98, Windows NT. You can also share with
Windows 95, Windows 98, Windows NT with Linux. You can also use SMB to share printers
connected to with Windows 95, Windows 98, Windows NT computers with
Cron Scheduler
Linux has a scheduler program called Cron.Cron is used to run commands , scripts , or programs
at scheduled times.
Licensing
Linux is licensed under the GNU General Public License.
Licensing for Red Hat Linux states that a person can make any number of copies of software and
distribute freely or charge a price for it.
Portability
Portability means softwares can works on different typeshardwares in same way.

Linux kernel
Linux kernel and application programs supports their installation on any kind of hardware
platform.Hierarchical File System Linux provides a standard file structure in which system files/
user,Files are arranged.
1.what are the features and facilities of linux?
2.Differentiate between multiprogramming and multitasking?
3.Explain Samba?
4.what is SMB?
Questions

1. Compare the features of UNIX and Linux?


2. What is the difference between Unix and Linux?

BASIC LINUX COMMANDS


Prepared By: Anjali Mohan
1.pwd (print working directory)
 Short for print working directory the pwd command displays the name of the current
working directory. 
 The pwd command reports the full path to the current directory. 
 This command has no arguments or keywords. 

 Syntax: pwd [option] 

OPTIONS:

 $pwd -P

path name printed will not contain symbolic links

 $ pwd –L

path printed may contain symbolic links

Examples:
To print current working directory,
enter: $pwd
Sample output: /home/mca

2.cal

  cal command is used to display the calendar. 


 Syntax: cal [options] [month]
[year] OPTIONS: 
 -1
Displays single month as output.
 -3
Displays prev/current/next month output.
 -s
Displays sunday as the first day of the week.
 -m
Displays Monday as the first day of the week.
 -j
Displays Julian dates (days one-based, numbered from
January 1).
 -y
Displays a calendar for the current year.

3.cd(change directory)
 Changes the directory. 
 Syntax: 
cd [DIRECTORY|~|./|../|-]

cd or cd ~ will always put you in your home directory.


cd . will leave you in the same directory you are
currently in(i.e. your current directory won't
change)

cd ~username will put you in username's home directory


cd dir will put you in a subdirectory. for example, if
you are in /usr, typing cd bin will put you in
/usr/bin, while cd /bin puts you in /bin.

cd .. will move you up one directory. So, if you


are /usr/bin/tmp, cd .. moves you to /usr/bin,
while cd ../.. moves you to /usr (i.e. up two
levels). You can use this indirection to access
subdirectories too. So, from /usr/bin/tmp, you
can use cd ../../local to go to /usr/local.
cd - will switch you to the previous directory
(UNIX only). For example, if you are in
/usr/bin/tmp, and go to /etc., you can type cd
- to go back to /usr/bin/tmp.

4.mkdir
 create a new directory (MaKe DIRectory) 
 Syntax: mkdir [options]directories 
Options:
 -v

Print help message for each directory created

 -p

Create inventory parent directory if don‘t exist

 m

Set the access mode for the new directories

Examples:
Open a terminal and use the mkdir command to create empty directories. The following
command would create a directory called mca:
aspire@aspire:~/Desktop$pwd
/home/aspire/Desktop
aspire@aspire:~/Desktop$mkdir mca
aspire@aspire:~/Desktop$ls -l
mca
The following command would create two directories within the current directory:
aspire@aspire:~/Desktop$mkdir one two
aspire@aspire:~/Desktop$ls -l
mca one two
5.rmdir

  rmdir is a command which will remove an empty directory on a Unix 


 Syntax : rmdir [options] directory_name 

Where name_of_directory corresponds with the name of the


directory one wishes to delete. p foo/bar/baz

Will first remove baz/, then bar/ and finally foo/ thus removing the
entire directory tree specified in the command argument.rmdir will not
remove a directory if it is not empty in UNIX.

 rmdir -r pascal :
Removes the directory and all files in that directory
 rmdir dir1 dir2 dir3
It will delete the empty directory dir1 dir2 dir3

6.ls

  The ls command is used to list files. 


 ‖ls‖ on its own lists all files in the current directory except
for hidden files. 
OPTIONS:
 ls -a

will list all files including hidden files (files with names beginning with a dot).

 ls –F
gives a full listing, indicating what type files are by putting a slash after
directories and a star after executable files (programs you can run).

 ls -l

gives a long listing of all files.

 ls –R

gives a recursive listing, including the contents of all subdirectories and their
subdirectories and so on.

 ls -t

lists the files in order of the time when they were last modified (newest first)
rather than in alphabetical order.

 ls -r

lists the files in the reverse of the order that they would otherwise have been
listed in.

 ls -lrt
will give a long listing, oldest first, which is handy for seeing which files in a
large directory have recently been changed.

7.cat

  cat is one of the most frequently used commands on Unix-like operating systems. 
 It has three related functions with regard to text files: displaying them, combining
copies of them and creating new ones. 
 Syntax: cat [options][file]… 
OPTIONS:
 -A
Show all.
 -b
Omits line numbers for blank space in the output.
 -e
A $ character will be printed at the end of each line prior to a new line.
 -E
Displays a $ (dollar sign) at the end of each line.
 -n
Line numbers for all the output lines.
 -s
If the output has multiple empty lines it replaces it with one empty line.
 -T
Displays the tab characters in the output.
 -v
Non-printing characters (with the exception of tabs, new-lines and form-feeds)
are printed visibly.

 The most common use of cat is to read the contents of files. For example, the following
will display the contents of a file named file1:

cat file1

 In the following example, the standard output of cat is redirected using


the output redirection operator to file2:

cat file1 > file2

That is, the output from cat is written to file2 instead of


being displayed on the monitor screen.

 The second role of cat is concatenation of copies of the contents of files.Because the
concatenation occurs only to the copies, there is no effect on the original files. 

For example, the following command will concatenate copies of the


contents of the three files file1, file2 and file3:

cat file1 file2 file3

 The third use for cat is file creation. For example, a new file named file1 can be created
by typing

cat > file1

then pressing the ENTER key and finally simultaneously pressing the CONTROL
and d keys.

 file with the same name. Thus the cautious user might prefer to instead use
the append operator in order to prevent unintended erasure. That is,

cat >> file1

8.head

 The head command in unix or linux system is used to print the first N lines from the file
to the terminal. 
 Syntax: head [-number | -n number] filename 

-number The number of you want to


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

Example:

Head -15 abc.txt

Display the first fifteen lines of abc.txt

9.tail

 Tail prints the last N number of lines from given input. By default, it prints last 10
lines of each given file 
 Syntax:tail[options][filename] 

Example:

 tail myfile.txt 

The above example would list the last 10 (default) lines of the file myfile.txt. 

 tail myfile.txt -n 100 

The above example would list the last 100 lines in the file myfile.txt. 

10.cp

 The cp command is used to copy files and directories. The copies become independent of
the originals 
 Syntax:cp[options] source destination 
 for example: 

 cp file2 file3 file4 dir1

It would copy the files named file2, file3 and file4 into a directory named
dir1:  cp –a dir1 dir2

copy the entire tree including permissions and links


 cp –p file1 file2

all of the attributes are preserved

11.rm


 Deletes a file without confirmation (by default). 
 You can enter more than one file specification on a command line by separating the file
specifications with spaces. 
Syntax: rm [-f] [-i] [-R] [-r] [filenames | directory]

-f Remove all file in a directory without prompting


the user.
-i Interactive. With this option, rm prompts for
confirmation before removing any files.
-R Same as -r option.
-r Recursively remove directories and
subdirectories in the argument list.
Filename A path of a filename to be removed.

12.mv

  to move one file or directory from one place to another place. 


 Also used for renaming a directory or file . 
 Syntax:mv [OPTION]... SOURCE DEST 

Options:

 $ mv -i file1 file2
Rename file1 to file2. if file2 exists prompt for confirmation before overwritting
it.

 $ mv -f file1 file2

Move the file without prompting evenif it is write over an exsisting target.
 $ mv -v file1 file2

mv -v will print what is happening during file rename, which is useful while
specifying shell metacharacters in the file name argument.

13.more

 It can be also used to display content of a file on terminal. 


  syntax: more [options] file_name 
 By default It do not provide scroll down facility like less to see the whole content but
show only that much content which fit into your screen. 

OPTIONS

 -c

Clear screen before displaying

 +n
Start up the file from the given number

 -e

Exit immediately after writing the last line of the last file in the argument list

 -n

Specify homany lines are printed on the screen.

Example:

$ more myfile

will show that much content of file which fit in screen.


$ more -100 + 50 myfile

will show 100 lines of file starting from line 50.

14.less

  can be used to see content of a file. 


 It allow you to display a large data in block and let you to scroll down, basically, it keep
 the screen at first line and let you scroll down. 
 If you do not use this, screen will set to the last line and you have to scroll up to see the
first line. you can exit the content by pressing q . 
 Syntax : less [options] file_name 

OPTIONS

 -d

Scrolls forward N number of lines.Default is one half of the screen.

 -u

Scrolls backward N number of lines.Default is one half of the screen.

 -f

Scroll forward to read the end of a file that is being modified.

Examples:
$ less myfile.txt
It will show content of file from the top, need to scroll down to see more content.
press q to exit the content.
Linux File Structure
Prepared By: Anju Raj
A file system is an organization of data and metadata on a storage device. A file system
contains the methods and data structures that an operating system uses to keep track of files on a
disk or partition. Linux follows single hierarchal directory structure. Everything starts from the
root directory, represented by '/', and then expands into sub-directories. Where DOS/Windows
had various partitions and then directories under those partitions, Linux places all the partitions
under the root directory by 'mounting' them under specific directories.
On a standard Linux system, the layout generally follows the scheme presented below.

/ --- |_ bin
|_ boot
|_ dev
|_ etc
|_ home
|_ lib
|_ lost+found
|_ media
|_ mnt
|_ net
|_ opt
|_ proc
|_ root
|_ sbin
|_ srv
|_ tmp
|_ usr
|_ var
The tree of the file system starts at a forward slash (/). This directory, containing all underlying
directories and files, is also called the root directory or the root of the file system.
Linux File System Structure Explained

1. / root directory

 Every directory under the root directory is on the root partition, unless it has a separate
entry in the full listing from df 
 Every single file and directory starts from the root directory. 
 Only root user has write privilege under this directory. 
 /root is root user‘s home directory, which is not same as /. 
 It is equivalent to the system drive (C:\ ) in Windows. 

3. /bin Essential command binaries

 Contains common binaries/commands, shared by the system, the system administrator


and the other users. 
 Essential commands used in single-user modes are located under this directory. 
 Example: ls, vi, cp, ping, grep, pwd, mkdir, rm, chmod, date, cat etc. 
 The equivalent of this in Windows is known as the system partition. 



4. /boot Static files of the boot loader

 Contains boot loader files 


  The startup files and the Kernel initrd, vmlinuz and grub data. 
 Contains everything required for the boot process except for configuration files not
needed at boot time and the map installer. 

5. /dev Device files

 Contains references to all the CPU peripheral hardware, which are represented as files
with special properties. 
 These include terminal devices, usb, or any device attached to the system. 
 Example: /dev/console, /dev/tty, /dev/ttyS0 etc 

6. /etc System configuration files

 Contains Host-specific system configuration 


 Contains configuration files required by all programs. 
 Local file used to control the operation of a program 
 Those files must be static and cannot be an executable binary 
  Startup and shutdown scripts to start/stop host specific individual programs. 
 Example: /etc/grub.conf, /etc/resolv.conf, /etc/host.conf etc 

7. /home User home directories

 Contains home directories of the common users. 


 Contains user specific config/settings and saved files 
 Users can store their personal files. 
 This directory is synonymous with ―C:\Documents and Settings\‖ in Windows 
 Example: /home/john. /home/user10 etc 

7. /lib System libraries

  Essential shared libraries and kernel modules 


 Supporting library files, includes files for programs (located under /bin and /sbin)
required by the system and the users. 
 Windows equivalent to a shared library would be a DLL (dynamically linked library) file 
 Example: /lib/libpthread-2.5.so, /lib/libgcc_s.so.1, /lib/libresolv.so.2 etc 

8. /lost+found Recovery files

 Files that were saved during failures are here. 


  Each partition has its own lost+found directory. 
 This is the place where corrupted files are placed when they are found during a filesystem
check. 
9. /media Removable media devices

 Contains subdirectories which are used as mount points for removeable media such as
floppy disks, cdroms and zip disks . 
 Examples: /media/cdrom, /media/floppy 

10. /mnt Mount directory

 Temporary mount directory where filesystems can be mounted. 


 When a file system no longer needs to be mounted, it can be unmounted with umount. 

11. /net Mount directoty for remote file systems

 Standard mount point for entire remote file systems 



13. /opt Optional application software packages

 Typically contains add-on and third party software. 

13. /proc Process information

  Contains information about system processes and resources as a virtual file system 
 Virtual filesystem documenting kernel and process status as text files, e.g., uptime,
 network. In Linux, corresponds to a Procfs mount 
 Example: /proc/uptime, /proc/cpuinfo etc. Also /proc/{pid} - contains information about
the process running with that particular pid 

14. /root Home directory for the root user

 Mind the difference between /, the root directory and /root, the home directory of the root
user. 

15. /sbin Essential system binaries

  Programs for use by the system and the system administrator. 


 /sbin should contain only binaries essential for booting, restoring, recovering, and/or
repairing the system in addition to the binaries in /bin. 
 Example: init, mount, iptables, reboot, fdisk etc 

16. /srv Service data

 Data for services provided by this system 


 Example: /srv/cvs contains CVS related data 

17. /tmp Temporary files

 Contains temporary files created by system and users. 


 Files under this directory are deleted when system is rebooted. 
 similar to the C:\Temp directory under Windows. 

18. /usr Secondary hierarchy for read-only user data
 Contains the majority of (multi-)user utilities and applications 
 Programs, libraries, documentation etc. for all user-related programs. 
 /usr/bin contains binary files for user programs. 
 /usr/sbin contains binary files for system administrators. 
 /usr/lib contains libraries for /usr/bin and /usr/sbin 
  /usr/local contains users programs that were installed from source. 
 This is where all of the program files will reside (similar to C:\Program Files in
Windows). 

20. /var Variable data

 Storage for all variable files and temporary files created by users 
  Content of the files that are expected to grow can be found under this directory 
 This includes — system/app log files (/var/log), packages and database files (/var/lib),
mail queue (/var/mail), print queues (/var/spool); lock files (/var/lock); temp files needed
 across reboots (/var/tmp). 
 Logs are generally stored in the C:\WINDOWS\system32\config\ directory in Windows. 

Linux File System Storage


Prepared By: Annmary

Boot block :

A Boot block located in the first few sectors of a file system. The boot block contains the initial
bootstrap program used to load the operating system. Typically, the first sector contains a boot
strap program that reads in a larger bootstrap program from the next few sectors, and so forth.
The blocks are normally a power of 2 in size (1024 is 2 to the 10th power). It Link to data blocks
holding boot code

Super block :

A Super block describes the state of the file system:


 the total size of the partition 

 the block size 

 pointers to a list of free blocks 
 the inode number of the root directory 

 magic number, etc. 

 File system status (mount point) 
 Number of allocated and free nodes 
 Link to lists of allocated and free nodes 
The superblocks contain information about the general size and ―shape‖ of the
file. system – they can be used to recover the system should corruption occur

Inode block :

The Inode blocks contain information about each file in the data block.The file information is
stored in records known as inodes.There is one inode for each file on the disk. They contain
information about the file, owner of the file, its file types, permissions and address.
Each file in the system is described with an inode (short for ``index nodes'‗ or ― Information
node ―) data structure.
The inode contains the specifics of the file – the permissions, last access time, the blocks
where data resides, etc.

UNIX distinguishes file data and information about a file (or meta-data)
File information is stored in a structure called inode
Attached to a particular
device Attributes
File Type
Number of hard links (they all share the same inode)
File length in bytes
Device identifier (DID)
User identifier (UID, file owner)
User group identifier (GID, user group of the file)
Timestamps: last status change (e.g., creation), modification, and access time
Access rights and file mode
Possibly more (non-POSIX) attributes, depending on the file system
Inode: Access Rights:
Classes of file
accesses user: owner
group: users who belong to the file‘s group, excluding the owner
others: all remaining users
Classes of access rights
read: directories: controls listing
write: directories: controls file status changes
execute: directories: controls searching (entering)
Additional file modes
suid: with execute, the process gets the file‘s UID
directories: nothing
sgid: with execute, the process gets the file‘s GID
directories: created files inherit the creator process‘s GID
sticky: loosely specified semantics related to memory management
directories: files owned by others cannot be deleted or
renamed

Inode: Data Block Addressing:


Every Inode has a table of block addresses
Addressing: direct, one-level indirect, two-levels indirect, ...

Fixed number of inodes per file system


Inodes do not contain file names, only file metadata

An inode is the ``handle'' to a file and contains the following information:


ice numbers for special devices.

DATA BLOCKS:
Data Blocks contain several types of files.

It contains users files, special files related to user data-regular files, directory files, symbolic link
files, character special files, block special files and socket system files

data blocks blocks containing the actual contents of files

Commands to access Inode numbers

Ls -i Command
The flag -i is used to print the Inode number for each file.

Df -i Command
df -i command displays the inode information of the file system.
$ ls -i
$ df -i
Stat Command Stat command is used to display file statistics that also displays inode number of
a file
$ stat a
LINK:

A link is a logical relationship between an inode and a file

Symbolic link: one file is a pointer or shortcut to another

Hard link: two files share the same data

File system has three main structural sections:


Superblock: Contains general information about the filesystem
○e.g., number of inodes and data blocks, size of each data block

The inode table: consists of several inodes, each of which describes a file or directory
○Unique inode number, file size, data block locations, last date modified, permissions, and
ownership

Data blocks: Data making up contents of a file


inode number with their target file

○Linked file and target file have different sizes


bolic link serves no function

UNIVESITY QUESTIONS
1. What do you mean by i-nodes ? Explain(MARKS 3) MAHATMA GANDHI
UNIVERSITY
MCA DEGREE EXAMINATION
MODEL QUESTION PAPER
(2011 Revised Syllabi)
LINUX STANDARD DIRECTORIES
Prepared By: Annie Xaviour

The Filesystem Hierarchy Standard (FHS) defines the structure of file systems on
Linux and other UNIX-like operating systems. However, Linux file systems also
contain some directories that aren‘t yet defined by the standard.
/ – The Root Directory

Everything on your Linux system is located under the / directory, known as the
root directory. The / directory as being similar to the C:\ directory on

Windows – but this isn‘t strictly true, as Linux doesn‘t have drive letters. While another
partition would be located at D:\ on Windows, this other partition would appear in
another folder under / on Linux.
/bin – Essential User Binaries

Contains several useful commands that are of use to both the system administrator as well
as non-privileged users. Usually contains the shells like bash, csh, etc.... and commonly used
commands like cp, mv, rm, cat, ls. This partition/volume contains almost everything

required for the boot process. It stores data that is used before the kernel begins executing
user programs. The equivalent of this in Windows is known as the system partition (not the
boot partition).

The /bin directory contains the essential user binaries (programs) that must be
present when the system is mounted in single-user mode. Applications such as Firefox are

stored in /usr/bin, while important system programs and utilities such as the bash shell
are located in /bin. The /usr directory may be stored on another partition – placing
these files in the /bin directory ensures the system will have these important utilities
even if no other file systems are mounted. The /sbin directory is similar – it contains
essential system administration binaries.
•cat →Utility to concatenate files to standard output
•chgrp →Utility to change file group ownership
•chmod →Utility to change file access permissions
•chown →Utility to change file owner and group
•cp →Utility to copy files and directories
•date →Utility to print or set the system data and time
•dd →Utility to convert and copy a file
•df →Utility to report filesystem disk space usage
•dmesg →Utility to print or control the kernel message buffer
•echo →Utility to display a line of text

•hostname →Utility to show or set the system's host name


•kill →Utility to send signals to processes
•ln → Utility to make links between files
•login → Utility to begin a session on the system
•ls → Utility to list directory contents
•mkdir → Utility to make directories
.mknod → Utility to make block or character special files
•more → Utility to page through text
•mount → Utility to mount a filesystem
•mv →Utility to move/rename files
•ps →Utility to report process status

•pwd →Utility to print name of current working directory


•rm →Utility to remove files or directories

•rmdir →Utility to remove empty directories


•sed →The `sed' stream editor
•sh →The Bourne command shell
•stty →Utility to change and print terminal line settings
•su →Utility to change user ID
•sync →Utility to flush filesystem buffers
•umount →Utility to unmount file systems
•uname →Utility to print system information
/boot – Static Boot Files

Contains everything required for the boot process except for configuration files not needed
at boot time and the map installer Stores data that is used before the kernel begins executing
user-mode programs . May include the system kernel (under symbolically linked)

The /boot directory contains the files needed to boot the system – for example, the

GRUB boot loader‘s files and your Linux kernels are stored here. The boot loader‘s
configuration files aren‘t located here, though – they‘re in /etc with the other
configuration files.
/cdrom – Historical Mount Point for CD-ROMs

The /cdrom directory isn‘t part of the FHS standard, but you‘ll still find it on Ubuntu
and other operating systems. It‘s a temporary location for CD-ROMs inserted in the system.
However, the standard location for temporary media is inside the /media directory.
/dev – Device Files

Linux exposes devices as files, and the /dev directory contains a number of special
files that represent devices. These are not actual files as we know them, but they appear as

files – for example, /dev/sda represents the first SATA drive in the system. If you wanted
to partition it, you could start a partition editor and tell it to edit /dev/sda.Block devices
are devices that store or hold data. Character devices can be thought of as devices that
transmit or transfer data.

This directory also contains pseudo-devices, which are virtual devices that don‘t actually
correspond to hardware. For example, /dev/random produces random numbers.

/dev/null is a special device that produces no output and automatically discards


all input – when you pipe the output of a command to /dev/null, you discard it.
/etc – Configuration Files

Contains all system related configuration files .Local file used to control the operation of a
Program. Those files must be static and cannot be an executable binary .

The /etc directory contains configuration files, which can generally be edited by hand
in a text editor. Note that the /etc/ directory contains system-wide configuration files –
user-specific configuration files are located in each user‘s home directory.
/home – Home Folders

The user home directories

•Accessible only to its owner and the system administrator


•Contains the user‘s personal configuration files

•This directory is synonymous with ―C:\Documents and Settings\‖ in Windows .

The /home directory contains a home folder for each user. For example, if your user
name is bob, you have a home folder located at /home/bob. This home folder
contains the user‘s data files and user-specific configuration files. Each user only has
write access to their own home folder and must obtain elevated permissions (become
the root user) to modify other files on the system.
/lib – Essential Shared Libraries

Contains kernel modules and those shared library images (the C programming code library)
needed to boot the system and run the commands in the root filesystem, ie. by binaries in
/bin and /sbin

•Windows equivalent to a shared library would be a DLL (dynamically linked library) file

The /lib directory contains libraries needed by the essential binaries in the /bin
and /sbin folder. Libraries needed by the binaries in the /usr/bin folder are located
in /usr/lib.
/lost+found – Recovered Files

Each Linux file system has a lost+found directory. If the file system crashes, a file
system check will be performed at next boot. Any corrupted files found will be placed in the
lost+found directory, so you can attempt to recover as much data as possible.
/media – Removable Media

Contains subdirectories which are used as mount points for removeable media such
as floppy disks, cdroms and zip disks . The /media directory contains subdirectories where
removable media devices inserted into the computer are mounted. For example, when you
insert a CD into your Linux system, a directory will automatically be created inside the
/media directory. You can access the contents of the CD inside this directory.

/mnt – Temporary Mount Points

This is a generic mount point under mounted (mount is to make a file system available to
the system) the file systems or devices.

•When a file system no longer needs to be mounted, it can be unmounted with umount

•mount /dev/hda2 /home


•umount /dev/hda2

Historically speaking, the /mnt directory is where system administrators mounted


temporary file systems while using them. For example, if you‘re mounting a
Windows partition to perform some file recovery operations, you might mount it at
/mnt/windows. However, you can mount other file systems anywhere on the system.
/opt – Optional Packages

The /opt directory contains subdirectories for optional software packages. It‘s
commonly used by proprietary software that doesn‘t obey the standard file system
hierarchy – for example, a proprietary program might dump its files in
/opt/application when you install it.
/proc – Kernel & Process Files

The /proc directory similar to the /dev directory because it doesn‘t contain standard
files. It contains special files that represent system and process information.
/root – Root Home Directory
The /root directory is the home directory of the root user. Instead of being located at

/home/root, it‘s located at /root. This is distinct from /, which is the system root
directory.
/run – Application State Files
The /run directory is fairly new, and gives applications a standard place to store
transient files they require like sockets and process IDs. These files can‘t be stored in
/tmp because files in /tmp may be deleted.
/sbin – System Administration Binaries

•/sbin should contain only binaries essential for booting, restoring, recovering, and/or
repairing the system in addition to the binaries in /bin.

The /sbin directory is similar to the /bin directory. It contains essential binaries that are
generally intended to be run by the root user for system administration.
/selinux – SELinux Virtual File System

If your Linux distribution uses SELinux for security (Fedora and Red Hat, for
example), the /selinux directory contains special files used by SELinux. It‘s similar to
/proc. Ubuntu doesn‘t use SELinux, so the presence of this folder on Ubuntu appears to
be a bug.
/srv – Service Data

The /srv directory contains ―data for services provided by the system.‖ If you were
using the Apache HTTP server to serve a website, you‘d likely store your website‘s files
in a directory inside the /srv directory.
/tmp – Temporary Files

Applications store temporary files in the /tmp directory. These files are generally
deleted whenever your system is restarted and may be deleted at any time by
utilities such as tmpwatch.
/usr – User Binaries & Read-Only Data

•The largest share of data on a system

•the most important directories in the system as it contains all the user binaries,
their documentation, libraries, header files, etc.... X and its supporting libraries, and
User programs like telnet, ftp, etc.... as well, can be found here.

•This is where all of the program files will reside (similar to C:\Program Files
in Windows).
The /usr directory contains applications and files used by users, as opposed to
applications and files used by the system. For example, non-essential applications are
located inside the /usr/bin directory instead of the /bin directory and non-essential
system administration binaries are located in the /usr/sbin directory instead of the
/sbin directory. Libraries for each are located inside the /usr/lib directory. The /usr
directory also contains other directories – for example, architecture-independent files
like graphics are located in /usr/share.

The /usr/local directory is where locally compiled applications install to by default – this
prevents them from mucking up the rest of the system.

/var – Variable Data Files

Contains variable data, files and directories the system must be able to write to during
operation, like system logging files, mail and printer spool directories, and transient and

temporary files .
Logs are generally stored in the C:\WINDOWS\system32\config\ directory in Windows.
The /var directory is the writable counterpart to the /usr directory, which must be read-

only in normal operation. Log files and everything else that would normally be written
to /usr during normal operation are written to the /var directory. For example, you‘ll
find log files in /var/log.
QUESTIONS
1 How is Linux Structured?

2.Explains the purpose of each linux standard directories, and even tells you what
directory is best to install software into. For most distros, software that doesn't come with
the distro probably should go into /usr/local/.
2. Exaplain the filesystem Hierarchy Structure.
File Naming Conventions

Prepared By:Anoop K.N

File names are only a convenience for users, and such operating systems identify files by their
inodes, which are numbers that are stored on the HDD in inode tables and which exist for all
types of files, rather than by their names or locations in directories.

File names in Linux can contain any characters other than (1) a forward slash ( / ), which is
reserved for use as the name of the root directory (i.e., the directory that contains all other
directories and files) and as a directory separator, and (2) the null character (which is used to
terminate segments of text). Spaces are permitted.

File names only use alphanumeric characters (mostly lower case), underscores, hyphens and
periods. Other characters, such as dollar signs, percentage signs and brackets, have special
meanings to the shell and can be distracting to work with. File names should never begin with
a hyphen.

A relatively small number of file names on a system consist only of upper case characters,
such as README, INSTALL, NEWS and AUTHORS. They are usually plain text files that
come bundled with programs and are for documentation purposes.

File names were limited to 14 bytes (equivalent to 14 characters) in early UNIX systems.
However, modern Unix-like systems support long file names, usually up to 255 bytes in
length. File names can be as short as a single character.

In some operating systems, such as MS-DOS and the Microsoft Windows systems, file names
consist of two parts: a user-designated name and an extension which is determined by the type
of file. The two are separated by a period.

PPT Notes

In Linux ,file names:

  Can be up to 256 characters 


  Can contain special characters, except for ‗/‘. 
  Can contain both uppercase and lowercase alphabets. 
  Are case-sensitive. 
 Should not contain a blank or a ta 
Absolute and Relative pathnames

Pathnames come in two flavours: absolute and relative.

To save typing long pathnames, many operating systems (including Unix/Linux and DOS) have
the concept of a current working directory. Every process in Linux can set a pathname to be
its current working directory. This working directory can be changed with the cd (change
directory) command. The current directory is used to make relative pathname references shorter.
More on that later.

Absolute pathnames start at the ROOT

A pathname that starts with a leading slash (indicating that the path starts at the nameless
ROOT directory) is called an absolute pathname.

An absolute pathname traverses the file system hierarchy always starting at the ROOT of the
hierarchy. The ROOT is written as a leading ―slash‖ character, i.e. ―/‖. Absolute pathnames always
start with this ROOT directory slash and descend through every directory name that leads down to
the destination, e.g. ―/home/user/file‖ or ―/usr/bin/grep‖ or ―/bin/ls‖ or ―/etc/passwd‖.

Your current working directory has no effect on an absolute pathname, because an absolute
pathname always starts at the ROOT and doesn‘t depend on your current directory.

Different files will never have the same absolute pathname. An absolute pathname always
refers to the same file.

Relative pathnames start in the current working directory

All other pathnames (with no leading slash) are called relative pathnames. These relative
pathnames are evaluated relative to the current working directory. Relative pathnames (no
leading slash) always start in the current directory, not in the ROOT directory.

A relative pathname traverses the file system hierarchy starting in the current (or ―working‖)
directory. The relative pathname specifies how to get from the current directory to the
destination file or directory. A relative pathname never stars with a slash, but it may contain
slashes. A relative pathname never includes the name of the current directory, since relative
pathnames always start in the current directory. The relative pathname ―foo/bar‖ starts in the
current directory, goes down into directory ―foo‖, to access object ―bar‖. The current directory of
a process determines what object is accessed by a relative pathname. Processes with different
current directories need different relative pathnames to get to the same place in the file system.

Because relative pathnames start in the current working directory, relative pathnames act as
if the current working directory were inserted in front of the pathname.
All relative pathnames are affected by changing the current working directory. Shells have
commands that let you change your current working directory so that you can type shorter
pathnames.

Differences between absolute and relative

Absolute pathnames always refer to the same, unique destination, since absolute pathnames
always start with the ROOT slash and don‘t depend on the current directory of a process. Every
process using an absolute pathname refers to the same, unique file system object, no matter
what the current directory of the process is. For example, the absolute pathname ―/etc/passwd‖
(starting with the ROOT slash) always means the same file anywhere it is used, ignoring the
current directory. Current directory is ignored for absolute pathnames.

Relative pathnames always start in the current directory of a process, so the destination
changes depending on the current directory of the process. The same relative pathname may
refer to different things in processes that have different current directories. Changing the
current directory changes the final destination of the relative pathname.

Examples of different relative pathnames

If the current working directory is ―/‖ (slash represents the ROOT of the file system), and the
absolute pathname of a file is /home/user/file, then a relative pathname to that file (from the current
working directory ―/‖) is home/user/file (no leading slash). If the current working directory is /home,
then a relative pathname to that same file (from the working directory /home) is user/file (no leading
/home). If the current directory is /home/user, then the relative pathname to that same file (from the
working directory /home/user), is just file (no leading /home/user).

Current Directory + Relative Pathname = Absolute Pathname

An Absolute Pathname is formed by taking the Current Directory and appending the
Relative Pathname. A current directory of /home/user plus a relative pathname of bin/script
equals an absolute pathanme of /home/user/bin/script.

To find a relative pathname, take the absolute pathname and remove the current directory
from the start. A current directory of /home/user removed from the start of an absolute
pathanme /home/user/bin/script leaves a relative pathname of bin/script.

One of the major reasons we use relative pathnames is because they are usually much shorter
than absolute pathnames.

PPT Notes

A path is a unique location to a file or a folder in a file system of an OS


Relative Path Names

Absolute or complete Path Names

Absolute or complete Path Names

directory(/).

ete path from start of actual file system


from / directory.

/home/ajce/Desktop/mca
/boot/grub/grub.conf

Relative Path Names Relative path is defined as path related to the present
working directory(pwd).
cd ajce

Locating Files and Directories

There may be times when you know a file or directory exists but you do not know where to find
it. There are several commands you can use to search for it, including find, locate, and which.

Find

The format of the find command is:

find path pattern

If you do not specify a path, find starts in the current working directory and looks through
all subdirectories for the specified pattern.

The find command has many options that you can review by entering man find at a shell
prompt. The most common option is -name, which tells find to search for all files and directories
with a certain string of letters in their name.
find . -name foo

The above command searches through the current working directory for all files with "foo"
in their name.

Locate

The format of the locate command is:

locate pattern

With locate, you can see every file or directory whose name contains the search criterion. For
example, to search for all files with the word finger in the name, type:

locate finger

The locate command uses a database to locate files and directories that have the word finger in
the file or directory name. The search results could include a file called finger.txt, a file called
pointerfinger.txt, a directory named /fingerthumbnails/, and so on. To learn more about locate,
read the locate man page (type man locate at a shell prompt).

The locate command works very quickly, as long as the database is up to date. That database is
automatically updated on a nightly basis through a cron job. cron is a small program that runs
in the background, performing various tasks (such as updating the locate database) at regularly
scheduled intervals. Refer to the Red Hat Enterprise Linux System Administration Guide for
more information on cron.

Which, whereis, whatis


which

The format of the which command is:

which command

which returns the location of binary, or executable, shell commands. The information
provided by whichis useful for creating application launchers.

which gedit
The above command returns the information /usr/bin/gedit.

whereis

The format of the whereis command is:

whereis command

The following command returns the locations of: the binary of find, the location of the
source code, and the location of the find man page.

whereis find
/usr/bin/find /usr/share/man/man1p/find.1p.gz /usr/share/man/man1/find.1.gz

whatis

The format of the whatis is:

whatis command

This command returnsinformation about the command from each of its man pages.

whatis lp

The above command returns:

lp (4) - line printer devices


lp(lp-cups) (1) - print files

QUESTIONS PAPERS

MODEL QUESTION PAPER MAHATMA GANDHI UNIVERSITY

6 Explain the file naming conventions in Linux.


Types of Files in Linux

Prepared By: Anusree R Nair

In Linux,information is stored in files.Therefore,in addition to user‘s program and data files,there


are special files that containinformation about directory contents or various input/output devices
connected to the Linux operating system.Therefore, all the information sent to the visual display
unit(VDU)is treated as if it were being sent to a file.
In Linux,there are three types of
files: *Ordinary
*Directory
*Special
So in practical we have total 7 types of files are there. And in Solaris we have 8 types.

Here are those files type. And you can see the file type indication at leftmost part of ―ls -l‖
command

1. Regular file(-)
2. Directory
files(d) Special files
3. Block file(b)
4. Character device file(c)
5. Named pipe file or just a pipe file(p)
6. Symbolic link file(l)
7. Socket file(s)

For your information there is one more file type called door files(D) which is present in Sun
Solaris as mention earlier. A door is a special file for inter-process communication between a
client and server(so total 8 types in Unix machines.).

Ordinary Files
All files created by a user are ordinary files.Ordinary files include all
data,program,object, and executable files.A user can modify ordinary files.
Directory Files
When you create a directory in Linux,a directory file is automatically createdby the
operating system.The directory file has the same as the directory and contains
information about the files stored in the directory.For example,the directory /home/Steve
contains a directory file called Steve in the directory /home.This directory file contains
information about all the files and directories in the directory Steve. A user cannot
modify a directory file.However when a file or subdirectory is added to the home
directory,the directory file is modified automatically by the Linux operating system.
The special entries ―.‖ and ―..‖ refer to the directory itself and to its parent directory
. (Dot) The special name for the current directory.
.. (Dot) (Dot) The special name for the directory above the current directory
Special Files
Most of the system filesin Linux are special files.Special files are usually associated with
input/output devices.Special files are stored in standard Linux directories,such as /dev and /etc. A
user can not modify special files.
* Character device files
* Block device files
* hard links
* symbolic links

Character Device Files


Character Device Files can read and write data ,one character at a time. A modem is an example
of a character device file.Character devices are also known as sequentially accessed devices.
Block Device Files
Block Device Files can access one block of data at a time.A block of data comprises either 512
or 1,024 bytes.The kernel reads or writes a minimum of one block of data at a time.The kernel
collects data in the memory and then makes the data available to a user.Block devices allow
random access,which makes input/output operations faster.An example of a block device is a
hard disk.
Hard Links
Hard Links are special files that allow asingle file to have multiple names.You can
Specify a hard link only for a file and not for a directory.These links are known as hard
links because they create a direct link to an inode.Each file system has its own inode
information database.Therefore,you can specify hard links for files only when they are
on the same file system. Hard linked files share the same inode and inode number .
*Must reside on the same file system
*To remove hard linked files, delete one of the linked files
Symbolic Links
Symbolic links are also known as soft links.Symbolic links are similar to hard links,but you can
specify symbolic links for files across different file systems. *Symbolic linked files do not share
the same inode and inode number with their target file
*Symbolic linked file is a pointer to the target file
*Data blocks in the linked file contain only a pathname for the target file
*Linked file and target file have different sizes
*If the target file is deleted, symbolic link serves no function

Types of Users in Linux


System Administrator
A System Administrator is responsible for the smooth operation of the Linux operating
system.The SA starts the system console on which the operating system is installed. The SA also
creates users and user groups on the Linux operating system.Additionally,the SA makes backups
to prevent data loss if the operating system crashes.In Linux,the SA is also known as the root
user.
File Owner
The user who creates s file is known as the owner of the file.The owner of a file can perform any
operation on that file,such as copying,deleting,or editing.

Group Owner
Consider the following situation
Project team of five people from ABC Telecommunications is working on a software
development project for a marketing agency.An analyst leads the team.The other four members
are programmers.The team is working on the Linux operating system.The data provided by the
agency is extremely confidential.Therefore,the data file needs to be created the analyst‘s home
directory.Each programmer needs to develop specific programs.In this situation ,all programmers
are the file owners of their own program files.A programmer might need to link a program with
another program to test the program.Therefore,each program also belongs to other
programmers.In this case,the project team of five users is collectively called the group owner of
the program files.In Linux ,you can define the users who belong to a group.In addition,similar to
a user name ,you can specify a name for the group of users.
Other Users
In the above example,all the users of the Linux operating system who are not members of the
project group are known as other users for the files of that group.Other users do not belong to the
particular group.For example,users who belong to the Accounting department may be treated as
other users for thed Marketing department.
Q:
Explain about types of files in
Linux? Explain special files?
What are the different types of users in Linux environment?
Differentiate between hard links and symbolic links?

File commands in linux


Prepared By: Arya Nair
1. cat

cat command concatenates files and print it on the standard output. If only one file name
is specified then ‗null‘ will be appended to the end of the content of given file name.
SYNTAX:
cat [OPTIONS] [FILE]...

Options : Description :
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to
a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one
empty line.
-T Displays the tab characters in the output.

cat can be used for file creation and also giving some content to the file.
»To Create a file
cat >FILE
example :
$ cat >file1
Hello world.
^D
»To add a Content
cat >>FILE
example :
$ cat >> file1
How are you.
^D
»To view the content in a file
cat FILE
example :
$ cat file1
Output :
Hello world.
How are you.

2. head

head command is used to display the specified number of lines from the beginning of the
file. Usually used to display first ten lines of a file.
SYNTAX:
head [options] filename

Options : Description :
-n To specify how many lines you want to display.
-n number The number option-argument must be a decimal integer
whose sign affects the location in the file, measured in lines.
-c number The number option-argument must be a decimal integer
whose sign affects the location in the file, measured in bytes.

Example :
$ head -1 file1
Output :
Hello world.

$ head –c 2 file1
Output :
He
3. tail
tail command is used to display the specified number of lines from the end of the file. By
default it displays last 10 lines of a file.
SYNTAX:
tail [options] filename

Options : Description :
-l To specify the units of lines.
-b To specify the units of blocks.
-n To specify how many lines you want to display.
-c number The number option-argument must be a decimal integer whose sign
affects the location in the file, measured in bytes.
-n number The number option-argument must be a decimal integer whose sign
affects the location in the file, measured in lines.

Example :
$ tail -1
file1 Output :
How are you.

$ tail –c 3 file1
Output :
you

4. cp

cp command copy files from one location to another. If the destination is an existing file,
then the file is overwritten; if the destination is an existing directory, the file is copied into the
directory (the directory is not overwritten). To copy files across directories, we have to specify
the complete path with the cp commands.
SYNTAX:
cp [OPTIONS]... SOURCE DEST
cp [OPTIONS] ... SOURCE ... DIRECTORY

Options : Description :
-i Prompts before overwriting.
-s Create a symbolic link.
-v Verbose – explain what is being done, in detail.

Examples :
Command Results

cp file1 file2 Copies the contents of file1 into file2. If file2 does not exist, it is created;
otherwise, file2 is overwritten with the contents of file1.
cp -i file1 file2 Like above however, since the "-i" (interactive) option is specified, if file2
exists, the user is prompted before it is overwritten with the contents of file1.

cp file1 dir1 Copy the contents of file1 (into a file named file1) inside of directory dir1.

cp -R dir1 dir2 Copy the contents of the directory dir1. If directory dir2 does not exist, it is
created. Otherwise, it creates a directory named dir1 within directory dir2.

5. rm

rm command is used to remove/delete the file from the directory.


SYNTAX:
rm [options..] [file | directory]

Options : Description :
-f Remove all files in a directory without prompting the user.

-i Interactive. With this option, rm prompts for confirmation before removing


any files.

-r (or) -R Recursively remove directories and subdirectories in the argument list. The dire
emptied of files and removed. The user is normally prompted for removal o
protected files which the directory contains.

6. mv

The mv command performs two different functions depending on how it is used. It will
either move one or more files to a different directory, or it will rename a file or directory. mv
command is different from cp command as it completely removes the file from the source and
moves to the directory specified, where cp command just copies the content from one file to
another.

SYNTAX:

mv [-f] [-i] oldname newname


Options : Description :
f This will not prompt before overwriting . mv -f will move the file(s)
without prompting even if it is writing over an existing target.

-i Prompts before overwriting another file.

To rename a file, it is used like this:

$ mv filename1 filename2

To move files to a different directory:


$ mv file1 file2 file3 directory

Examples of mv and its options include:

Command Results

mv file1 file2 If file2 does not exist, then file1 is renamed file2. If file2 exists, its contents
are replaced with the contents of file1.

mv -i file1 file2 Like above however, since the "-i" (interactive) option is specified, if file2
exists, the user is prompted before it is overwritten with the contents of file1.

mv file1 file2 The files file1, file2, file3 are moved to directory dir1. dir1 must exist or mv
file3 dir1 will exit with an error.

mv dir1 dir2 If dir2 does not exist, then dir1 is renamed dir2. If dir2 exists, the directory
dir1 is created within directory dir2.

7. more and less

cat command is used to display the content of a file on the screen. If the displayed file is
large, the entire content of the file scroll up the screen. To view a file one at a time, you can use
the more or less command.
more command is used to display the content of a file one screen at a time. You cannot
scroll up after scrolling down.
SYNTAX:
more [options] filename

Options : Description :
-c Clear screen before displaying.
-e Exit immediately after writing the last line of the last file in the argument
list.

-n Specify how many lines are printed in the screen for a given file.

+n Starts up the file from the given number.

less command is used to display text in the terminal screen. You can scroll up while
viewing the content of a file. The less command is faster than the more because the less
command accepts and caches data in the memory. Therefore the data is available in the memory,
and you can move up and down a screen faster. To display the file from the specified line, enter
the line number followed by colon(:). It allows Forward and backward movement in the file.
SYNTAX:
less [options] filename
Options : Description :
-c Clear screen before displaying.

+n Starts up the file from the given number.


:p Examine the pervious file in the command line list.
:d Remove the current file from the list of files.

QUESTIONS ;
1. Explain various files and directory types in Linux.
2. Consider that marks.txt is a file that contains one record per line (comma
separated fields) of the student data in the form of studentid, student name,
Telugu marks, English marks, Maths marks, Science marks, Social marks. Write
an awk script to generate result for every student in the form of studentid, student
name, Total marks and result. Result is PASS if marks is >= 30 in Telugu and
English , and if marks >= 40 in other subjects. Result is FAIL otherwise.
c) Write briefly on sed, chmod, df, comm, fgrep and sort commands with examples.
3. What will be the output of the command rm *i* .

FILE COMPARISONS
Prepared By: Arya Surendran
There are three commands for comparing files in linux.
compare(cmp)
difference(dif
f)common(co
mm)

cmp
cmp linux command compares two files and tells you which line numbers are different.That
is, examines two files byte by byte.
Syntax:
cmp [options..] file1 file2

Options:

- c Output differing bytes as characters.


-l Print the byte number (decimal) and the differing byte values
(octal) for each difference.
-s Prints nothing for differing files, return exit status only.

Example :

To provide examples for this command, lets consider two files


: file1.txt
$ cat file1.txt

Hi My name is Himanshu
file2.txt
$ cat file2.txt

Hi My name is Himanshu Arora


$ cmp file1.txt file2.txt
Output is file1.txt file2.txt differ: byte 23, line 1
diff
diff command is used to find differences between two files.That is,it shows the line by line
differences between two files.
Syntax:
diff [options..] from-file to-file
Options:

-a Treat all files as text and compare them line-by-line.


-b Ignore changes in amount of white space.
-c Use the context output format.
-i Ignore changes in case; consider upper- and lower-case letters equivalent.
-r When comparing directories, recursively compare any subdirectories found.
-s Report when two files are the same.
-w Ignore white space when comparing lines.
-y Use the side by side output format.

Example:
To compare the contents of two files:
diff email addresses
Here are the contents of files email and addresses used in this example.
email addresses
1 John erpl08@ed 1 John erpl08@ed
2 Joe [email protected] 2 Joe [email protected]
3 Kim [email protected] 3 Jean [email protected]
4 Keith keith@festival 4 Jim jim@frolix8
5 Kim [email protected]
6 Keith keith@festival
This displays a line by line difference between the file email and
addresses. The output will be:
2a3,4
> Jean [email protected]
> Jim jim@frolix8

comm
Select or rejects lines common to two files.That is, compare two sorted files line by line.
Displays the results in three columns.
 The left column contains unique lines in file 1 
 The center column contains unique lines in file 2 
 The right column contains lines found in both files 
Syntax:
comm [option s..] file1 file2
Example:
$ cat name_list.txt
Bram Moolenaar
Ken Thompson
Linus Torvalds
$ cat name_list_new.txt
Bram Moolenaar
Dennis Ritchie
Richard Stallman
$ comm name_list.txt name_list_new.txt
Bram Moolenaar
Dennis Ritchie
Ken Thompson
Linus Torvalds
Richard Stallman

DIRECTORY COMMANDS
Prepared By: Arya VB
Pwd
Print Working Directory. pwd command prints the full filename of the current working directory.
SYNTAX: pwd [options]
Options:

-P :The pathname printed will not contain symbolic links. -


L :The pathname printed may contain symbolic links.
Example
$pwd
Home/student
Here Home/student is the directory in which the user is currently working.
cd
cd command is used to change the current directory to a specified directory. Type cd followed by
the name of a directory to access that directory.
SYNTAX: cd [directory | ~ | ./ | ../ | - ]

Options

-L :Use the physical directory structure. -P


:Forces symbolic links.
Example
$cd mydirectory
Here the user changes the working directory to mydirectory.
$cd ..
The double period(..)option with the cd command to switch to the parent directory of the
current directory.
$cd
When you specify the cd command without any path,the current directory switches to the
home directory.

ls

ls command lists the files and directories under current working directory. It can be used to
display the names of files and subdirectories that are stored in a directory.
SYNTAX: ls [Options]…[file]
Options
-l :Lists all the files, directories and their mode, Number of links, owner of the file, file size,
Modified date and time and filenam

-t :Lists in order of last modification time -a


:Lists all entries including hidden files -d
:Lists directory files instead of contents -p
:Put slash at the end of each directories -u
:Lists in order of last access time
-I :Display inode information -ltr
:Lists files order by date -lSr
:Lists files order by file size
Example
jwallin@bomb20:~$ ls
Desktop Downloads host Music Public Videos
Documents examples.desktop mount_mac Pictures Templates
Mkdir
mkdir (make directory)command is used to create one or more directories
SYNTAX: The Syntax is mkdir [options] directories
Options
-m :Set the access mode for the new directories
-p :Create intervening parent directories if they don't exist -v
:Print help message for each directory created.
Example
$mkdir progfiles
Here a subdirectory progfiles is created in the current directory. However ,the
new directory does not become the current directory. You can also specify the
complete path with the mkdir command.
$mkdir -p path/test/test1
Rmdir

Rmdir(remove directory) command is used to delete/remove a specified directory and its


subdirectories.

SYNTAX: rmdir [options..] Directory


Options

-p : Allow users to remove the directory dirname and its parent directories which become
empty.
Example
$rmdir pgmfiles
Here pgmfiles directory is deleted.
You can also specify the complete path with the rmdir
command. $rmdir /home/student/pgmfiles
The above command removes pgmfiles directory,which is located in student‘s home
directory.

QUESTIONS

1. Write a linux command to display the lines from 25 to 45 of /etc/passwd


file. Write a linux command to display the directories in /etc

Text Editors
Prepared By: Athulya S Kumar
A text editor is used to create and manage text files and documents. An editor is
application software, which is usually bundled with an operating system (OS).A text editor has a
wide variety of application such as:
 Creating and Maintaining documents 
  Writing programs and Utilities 
 Writing mail Messages 

Functions of a Text Editor


A text editor should allow you to perform some basic functions such as:
 Creating a File
An editor should allow you to create a file and write data to it. It should allow you
to store the file anywhere on your storage media.
 Opening an Existing File
An editor should allow you to open an existing file, modify its contents, and save
the file with the changes .In addition an editor should also open multiple documents at a
time and the files created by other editors.
 Copying and Pasting Text
An editor should allow you to copy and paste because this feature facilitates the
process of document creation.
 Searching text
An editor should allow you to search for a particular expression or word. Many
editors support global search and replace operations. This feature allows changes to
multiple instances of a particular file.
 Handling large amount of data.
An editor should be capable of handling large files. Some editors are built in such
a way that they can only handle a specific amount of data in memory. They fail if the file
size is very large.
Editors Available with Linux
 Vi(visual editor) 
  Vim(visual editor improved) 
  Emacs(edit macros editor) 
  Sed(stream editor) 
  Ed(line editor) 
  Red(restricted ed editor) 
 Pico 
The VI editor
The VI editor is a visual editor used for creating and editing text files containing data,
documents or programs. It displays the content of files on the screen and allows a user to add,
insert, delete, or change parts of the text. It is amongst the oldest editors available on UNIX
platforms and is available for all the variants of Unix/Linux.
In Red Hat Linux, VI is a symbolic link to the vim editor. The vim editor is an improved
version of the vi editor. The view editor is another symbolic link to the vim editor, and is used to
open the file in the read-only mode. Therefore you can start the vim editor by typing the vi or
view command. However, the view command opens the file in the read-only mode.

FILE PERMISSION
Prepared By: Balu Abraham
File ownership is an important component of UNIX that provides a secure method for storing
files. Every file in UNIX
has the following attributes:
Owner permissions: The owner's permissions determine what actions the owner of the file can
perform on the
file.
Group permissions: The group's permissions determine what actions a user, who is a member of
the group that
a file belongs to, can perform on the file.
Other (world) permissions: The permissions for others indicate what action all other users can
perform on the
file.
The Permission Indicators:
While using ls -l command it displays various information related to file permission as follows:
$ls -l /home/amrood
-rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
Here first column represents different access mode ie. permission associated with a file or
directory.
The permissions are broken into groups of threes, and each position in the group denotes a
specific permission, in this
order: read (r), write (w), execute (x):
The first three characters (2-4) represent the permissions for the file's owner. For example -rwxr-
xr-- represents
that onwer has read (r), write (w) and execute (x) permission.
The second group of three characters (5-7) consists of the permissions for the group to which the
file belongs.
For example -rwxr-xr-- represents that group has read (r) and execute (x) permission but no write
permission.
The last group of three characters (8-10) represents the permissions for everyone else. For
example -rwxr-xr--
represents that other world has read (r) only permission.
File Access Modes:
The permissions of a file are the first line of defense in the security of a Unix system. The basic
building blocks of Unix
permissions are the read, write, and execute permissions, which are described below:
1. Read:
Grants the capability to read ie. view the contents of the file.
2. Write:
Grants the capability to modify, or remove the content of the file.
3. Execute:
User with execute permissions can run a file as a program.
Directory Access Modes:
Directory access modes are listed and organized in the same manner as any other file. There are a
few differences that
need to be mentioned:
1. Read:
Access to a directory means that the user can read the contents. The user can look at the
filenames inside the directory.
2. Write:
Access means that the user can add or delete files to the contents of the directory.
3. Execute:
Executing a directory doesn't really make a lot of sense so think of this as a traverse permission.
A user must have execute access to the bin directory in order to execute ls or cd command.
Changing Permissions:
To change file or directory permissions, you use the chmod (change mode) command. There are
two ways to use
chmod: symbolic mode and absolute mode.
Using chmod in Symbolic Mode:
The easiest way for a beginner to modify file or directory permissions is to use the symbolic
mode. With symbolic
permissions you can add, delete, or specify the permission set you want by using the operators in
the following table.
Chmod operator Description
+ Adds the designated permission(s) to a file or directory.
- Removes the designated permission(s) from a file or directory.
= Sets the designated permission(s).
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as
follows:
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l
so you can see the
permission changes:
$chmod o+wx
testfile $ls -l testfile
-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10
testfile $chmod u-x testfile
$ls -l testfile
-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod g=r-x testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Here's how you could combine these commands on a single line:
Here's how you could combine these commands on a single line:
$chmod o+wx,u-x,g=r-x testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Using chmod with Absolute Permissions:
The second way to modify permissions with the chmod command is to use a number to specify
each set of permissions
for the file.
Each permission is assigned a value, as the following table shows, and the total of each set of
permissions provides a
number for that set.
Number Octal Permission Representation Ref
0 No permission ---
1 Execute permission --x
2 Write permission -w-
3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx
4 Read permission r--
5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x
6 Read and write permission: 4 (read) + 2 (write) = 6 rw-
7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as
follows:
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l
so you can see the
permission changes:
$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 743 testfile
$ls -l testfile
-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 amrood users 1024 Nov 2 00:10 testfile
Changing Owners and Groups:
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the
permissions mentioned
above are also assigned based on Owner and Groups.
Two commands are available to change the owner and the group of files:
1. chown: The chown command stands for "change owner" and is used to change the owner of a
file.
2. chgrp: The chgrp command stands for "change group" and is used to change the group of a
file.
Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as follows:
$ chown user filelist
The value of user can be either the name of a user on the system or the user id (uid) of a user on
the system.
Following example:
$ chown amrood testfile
$
Changes the owner of the given file to the user amrood.
NOTE: The super user, root, has the unrestricted capability to change the ownership of a any file
but normal users can
change only the owner of files they own.
Changing Group Ownership:
The chrgp command changes the group ownership of a file. The basic syntax is as follows:
$ chgrp group filelist
The value of group can be the name of a group on the system or the group ID (GID) of a group
on the system.
Following example:
$ chgrp special testfile
$
Changes the group of the given file to special group.
SUID and SGID File Permission:
Often when a command is executed, it will have to be executed with special privileges in order to
accomplish its task.
As an example, when you change your password with the passwd command, your new password
is stored in the file
/etc/shadow.
As a regular user, you do not have read or write access to this file for security reasons, but when
you change your
password, you need to have write permission to this file. This means that the passwd program
has to give you additional
permissions so that you can write to the file /etc/shadow.
Additional permissions are given to programs via a mechanism known as the Set User ID (
SUID) and Set Group ID (
SGID) bits.
When you execute a program that has the SUID bit enabled, you inherit the permissions of that
program's owner.
Programs that do not have the SUID bit set are run with the permissions of the user who started
the program.
This is true for SGID as well. Normally programs execute with your group permissions, but
instead your group will be
changed just for this program to the group owner of the program.
The SUID and SGID bits will appear as the letter "s" if the permission is available. The SUID "s"
bit will be located in
the permission bits where the owners execute permission would normally reside. For example, the
command
$ ls -l /usr/bin/passwd
-r-sr-xr-x 1 root bin 19031 Feb 7 13:47 /usr/bin/passwd*
$
Which shows that the SUID bit is set and that the command is owned by the root. A capital letter S in the
execute
position instead of a lowercase s indicates that the execute bit is not set.
If the sticky bit is enabled on the directory, files can only be removed if you are one of the following
users:
The owner of the sticky directory
The owner of the file being
removed The super user, root
To set the SUID and SGID bits for any directory try the following:
$ chmod ug+s dirname
$ ls -l
drwsr-sr-x 2 root root 4096 Jun 19 06:45 dirname
$

REDIRECTION
Prepared By:Bony Kurian

•The process of changing standard input, standard output and the standard error files is known as
redirection.
•Using redirection, input to a command can be taken from a file instead of the keyboard.
•Output of a command or error can be written into a file instead of displaying it in the screen.
•Three types of redirection are input ,output and error redirection

Input Redirection :
Input to a command can be taken from a file instead of the
typing. The symbol used for redirecting the input is <
example:-
cat < test1 <enter>
The commands reads from the test1 as input and display it on the
screen. Input is taken from the disk file instead of the standard input file.
cat 0< test1 <enter>
0 indicates input redirection.

Output Redirection :
The output of command can be stored in the file instead of displaying it in the
screen. The symbol used for redirecting the output is >
example:-
cat test1 > test2
The output of the cat command is written into the disk file test2 instead of displaying it in the
screen.
A file to which output redirected is created on the disk first as empty, if the file exists, its
contents are deleted.To add output of the command at the end of the a file instead of overwriting
the existing contents of the file, we use >> symbol.

cat test1 >> test2

We can also use as follows


cat test1 1> test2
cat test1 1>> test2
1 indicates output redirection.

Error Redirection :
Using error redirection error messages can be written into a disk file instead of displaying it in
the screen.
example:-
cat datafile 2> error-msg
If the file datafile does not exist in the current directory, Linux generates an error message and
write it into error-msg file.

Example: Redirect error of a command to a file and output to the screen.


ls -hrtfd 2> file3.txt
Example: Redirect and append error to a file and output to the screen.
ls -wertdf 2>> file4.txt
Example: Redirect both output and error to a file
ls -ewrdter &> file5.txt

Advanced Redirection :

File descriptors:
>& <& Redirect output of a command to a file for future reference.

Example: Redirect output of fdisk -l to a file file1.txt fdisk -l > file1.txt

tee command:

tee(T) command is a special command which will redirect the output to a file as well as screen
at same time,
Example: fdisk -l | tee file6.txt

xargs command:

xargs command is one more special command which will redirect output of a command and feed
it as input to other commands.

Example: ls *.sh | xargs grep bash

- (hyphen or dash) Operator:


This operator will act as both input as well as output redirect operator.

FILTERS
Prepared By: Dany N Antony
A filter is a program that takes input from the standard input file,processes it,and send the
output to the standard output file. One of the most common uses of filter is to restructure output.
Linux provides various filters,such as
1.The cat Filter
The cat command is considered as one of the most frequently used commands on Linux like
operating systems. Cat command is used to display the contents of a file on terminal. Cat when
supplied with more than one file will concatenate the files without any header information.
Syntax:
cat filename
Examples:
 To Create a file 

# cat >hello

welcome

^D

 To add a Content 

# cat >>hello

welcome to my college
^D

 To view the content in a file 



# cat hello

welcome to my college

2.The grep Filter

The grep command searches for the pattern specified by the pattern parameter and writes
each matching line to standard output. The patterns are limited regular expressions in the style of
the ed or grep command. The grep command uses a compact non-deterministic algorithm.

Syntax
grep regular_expression [filename]
Example:
ls –l | grep ^a | wc -l

Count the files in the current directory that begin with the letter a.

Options Descriptions

This option with the grep filter to display each line matching the specified
-n pattern,along with the line number. The line number is printed at the
beginning of the line.

-c This option to display only a count of the lines that match the specified
pattern.
-v This option to display all the lines that do not match the specified pattern.

3.The wc Filter
The wc command counts the number of lines, words, and bytes in the files specified by
the file parameter. The command writes the number of newline characters, words, and bytes to
the standard output and keeps a total count for all named files.
Syntax
wc [-lwc] [filename/s]
Example:
$ wc text
2 7 29 text
The file text has 2 lines,7 words,and 29 characters.
Options Descriptions
-l Displays the number of lines.
-w Displays the number of words.
-c Displays the number of characters.

4.The cut Filter


Cut command in Linux is used to select sections of text from each line of files. The cut
command to select fields or columns from a line by specifying a delimiter or you can select a
portion of text by specifying the range or characters.
Syntax
cut [options] [filename/s]
Options Descriptions
-f<column_number(s)> Displays the specified columns.
-c<character_number(s)> Displays the specified characters.
-d<column_delimiter> Specifies the column delimiter.

Example:

$ cat file.txt
unix or linux os
is unix good os
is linux good
os cut -c4
file.txt x

u
l
5.The paste Filter
The paste command merges the lines from multiple files. The paste command
sequentially writes the corresponding lines from each file separated by a TAB delimiter on the
linux terminal.
Syntax
paste [options] files-list

Options Descriptions
-d Specify of a list of delimiters.
-s Paste one file at a time instead of in parallel.

Examples:
For the following examples, assume that names.txt is a plain-text file that contains the following
information:
Mark Smith
Bobby Brown
and that numbers.txt is another plain-text file that contains the following information:
555-1234
555-9876
The following example shows the invocation of paste with names.txt and numbers.txt as well as
the resulting output:
$ paste names.txt numbers.txt
Mark Smith 555-1234
Bobby Brown 555-9876
6.The sort Filter

The sort command sorts lines in the files specified by the file parameter and writes the result to
standard output. If the file parameter specifies more than one file, the sort command concatenates
the files and sorts them as one file.

Syntax

sort [options]... [file]

Options Descriptions
-b Ignores spaces at beginning of the line.

-c Check whether input is sorted; do not sort


-d Uses dictionary sort order and ignores the punctuation.
-f Ignores caps.

Examples:
$cat names.txt
Jins
Amal
Mebin
$sort names.txt
Amal
Jins
Mebin
7. The tr Filter
The tr filter is used to replace one set of characters with another. The tr command deletes or
substitutes characters from standard input and writes the result to standard output.

Syntax

tr [option] [string1] [string2]

Options Descriptions
-d Deletes each character from standard input that is contained in the
string specified by string1.
-c Specifies that the value of string1 be replaced by the complement of the
string specified by string1.

Example:

echo "12345678 9247" | tr 123456789 computerh

This example takes an echo response of '12345678 9247' and pipes it through the tr
replacing the appropriate numbers with the letters.

PIPES
Prepared By: By Deepa Kuruvila

One of the most powerful advantages of Linux is the use of pipes. A pipe takes stdout
from the previous command and sends it as stdin to the next command. All commands in a pipe
run simultaneously.
The vertical bar (|) which denote the pipe character indicates that the output of the
command typed before the | is to sent as input to the command typed after the |.
For example,to display all the contents of the current directory, you need to type the following
commands:
$ ls > tempfile $
more tempfile

Here, the ls command stores a list of the directories in the file tempfile.
The tempfile file is then used as input by the more command.

By using the Linux pipe feature, the above two steps can be combined and executed as a single
command without creating a temporary file,as shown below:

$ ls | more
You can use the pipe feature to perform complex tasks by combining the commands available in
linux
When you use the pipe feature, you can specify multiple commands or filters. Some of the
examples of using pipe is given below:
ls | wc -l
ls | wc –l >
countfile who | sort
who | sort > sortdlist
To understand how the the pipe command works,consider the example in the figure below:

pipe
output

Input ls more

Command 1 Command 2

(gives the output to (takes the input from


command 2) command 1)
Example:

The following is a sample output of the ls - l commands:

-rw-rw-r--1 steve steve 1384 Sep 24 06:32 DEADJOE


drwxr-xr-x5 steve steve 1024 Sep 20 23:30 Desktop
drwx------ 2 steve IRDTECH 1024 Sep 22 09:00 Mail
-rwxr-xr-x 1 root root 12691 Sep 26 01:46 a.out
drwx------ 2 steve IRDTECH 1024 Sep 27 23:20 mail
drwx------ 2 steve IRDTECH 1024 Sep 28 22:21 nsmail
-rw-rw---- 1 steve steve 58 Sep 22 03:44 program.cc
-rwxrwxrwx 1 steve IRDTECH 691 Sep 22 23:55 test

Based on the above output ,some examples of the pipe feature are given below:

To display the names of all the ordinary files in the current directory,you need to type the
following command:

$ ls –l |grep ”^-“ |tr –s “ “ |cut –d “ “ –f 9


Output

a.out
program.cc
test

In the above syntax ,the output of the ls -l command is provided as input to the grep command.
The ls –l command displays a detailed list of files in the current directory. The grep command
extracts all the ordinary files. This output is then given to the tr command, which replaces
multiple spaces with a single space. The cut command takes this as input and extracts the ninth
field ,which is the file name ,and displays the file name.
To display the file names in the current directory along with their files size, you need to type the
following command:
$ ls -l | tr -s “ “ | cut –d “ ” –f 5,9 |more
Output
1024 Desktop
1024 Mail
12691 a.out
1024 mail
1024 nsmail
58 program.cc
691 test

The tee Command


The tee command is used to store and view (both at the same time) the output of any other
command .The tee command copies standard input to standard output and at the same time
copies it to one or more files.
Syntax:
tee options file-list

In linux ,the intermediate output in a pipe is note saved on the disk. However, at times ,you
might need to redirect the standard output of a command to another command or save the output
on the disk for later use.
You can use the tee command to redirect the standard input and write it to standard output or to
file(s).If the file in which data is to be stored does not exist ,the file is created by the operating
system. If the file exists, the contents of the file are overwritten.
You can use the –a option to append contents to an existing file.

$ ls | tee –a file

Example 1:

$ cat temp |tee temp1 temp2


The above command displays the contents of the file temp on the screen and also writes to the
files temp1 and temp2 .
Example 2:

$sort number | tee sort-numbers |more


In the above command, the file numbers is sorted ,and the data is redirected to the tee command.
The tee command creates the file sort-numbers ,and stores the data in the file. The tee command
also redirects data as input to the more utility.
The following figure depicts how the tee command works:

number sort tee

Sort-
numbers

fig:The tee command

Questions:

1) Explain pipes in Linux with suitable examples.

PDF to Word

You might also like