UNIX
UNIX
TO UNIX
UNIX OPERATING SYSTEM
Summary of UNIX
UNIX is a groundbreaking operating system developed
in the 1970s by Ken Thompson, Dennis Ritchie, and
others at AT&T Bell Labs. It serves as the foundation
for many modern operating systems like Linux,
macOS, and POSIX-compliant systems. Initially
designed for developers, UNIX played a crucial role in
software development and computing environments.
Key Features:
     Multiuser & Multitasking: Supports multiple
      users and simultaneous processes.
     Shell Scripting: Enables automation through
      powerful command-line scripts.
     Security: Implements robust security models with
      user permissions.
     Portability: Runs on various hardware platforms.
     Process Tracking & Communication: Manages
      CPU usage, disk space, and supports inter-user
      communication.
System Structure:
UNIX follows a layered architecture:
  1. Hardware – The physical components.
  2. Kernel – The core of the system, managing
     memory, files, and processes.
  3. Shell – Acts as an interface between users and the
     kernel, processing commands.
  4. Application Layer – Executes external
     applications.
UNIX vs. Linux:
     Linux is an open-source UNIX-like OS, whereas
      UNIX is proprietary.
     Linux supports GUI and CLI, while traditional
      UNIX is mostly CLI-based.
     Linux is more portable and flexible than UNIX.
Advantages of UNIX:
✅ Highly stable and secure
✅ Scalable and flexible for various computing needs
✅ Efficient command-line interface for advanced
users
Disadvantages of UNIX:
❌ Complex for beginners
❌ Costly in some versions
❌ Limited software availability and lack of
standardization across versions
Despite its learning curve, UNIX remains widely used in
enterprise computing, scientific research, and
web servers, influencing modern OS development
significantly. 🚀
UNIX ARCHITECTURE
Well, we know that Unix is an Operating System. Like
any other Operating System, Unix also acts as an
interface between the user and the hardware, i.e. the
user and the computer itself. Unix mainly focuses on
the concept of Kernel and Shell division of an Operating
System due to which it is so powerful.
     Kernel: The kernel is a program in the Operating
      System software that keeps on running in the
      background when the machine is on and it is
      responsible for allocating the resources to the
      processes, handling and coordinating the multiple
      processes running together.
     Shell: However, since the kernel is such an
      essential program in the Operating System and
      performs almost all of the major tasks, it should
      not be directly accessible to the user. So, there is a
      program between the user and the kernel that
      helps the user interact with the kernel. This
      program is called the shell.
The Unix architecture has 4 layers. These layers are as
shown below:
Hardware: Hardware is the most simple and least
powerful layer in the Unix Architecture. Hardware is the
components that are humanly visible. Whatever
hardware is connected to a Unix operating system-
based machine, comes in the hardware layer.
Kernel: This is the most powerful layer of the Unix
architecture. The kernel is responsible for acting as an
interface between the user and the hardware for the
effective utilization of the hardware. The kernel handles
the hardware effectively by using the device drivers.
The kernel is also responsible for process management.
So, the main 2 features of the kernel are process
management and file management.
     Process Management: The processes that execute
      within the operating system require a lot of
      management in terms of memory being allocated
      to them, the resource allocation to the process,
      process synchronization, etc. All this is done by the
      Kernel in Unix OS. This is done using various
      Operating System Techniques like paging, framing,
      virtual memory, swapping, context-switching, etc.
     File Management: File management involves
      managing the data stored in the files. This also
      includes the transmission of data stored in these
      files to the processes as and when they request it.
Shell: We understood the importance of the kernel and
that it handles most of the important and complex
tasks of Unix OS. Since the kernel is such an important
program of the Unix Operating System, its direct access
to the users can be dangerous. Hence, the Shell comes
into the picture. Shell is an interpreter program that
interprets the commands entered by the user and then
sends the requests to the kernel to execute those
commands. When the execution of the process is
completed, the shell again sends a request to the
kernel to display the program/information on the screen
to the user. So, Kernel is an interface between the user
and the hardware and the Shell is an interface between
the user and the Kernel. The shell can be used for
opening a file, writing into the files, executing
programs, etc. There are 3 types of shells in the Unix
Operating system.
     Bourne Shell (sh): It is the most widely available
      shell on Unix OS devices across the world. This was
      the first shell available in the Unix OS. It is simply
      called a shell.
     C Shell (csh): The University of California (Berkeley)
      developed C Shell is another Unix shell that
      removes some of the obsolete features or
      problems from the Bourne Shell. So, it enhances
      the performance of the Bourne Shell.
     Korn Shell (ksh): The name of the Korn Shell is
      based on its creator, David Korn. This shell
      enhances the C shell further by removing the
      shortcomings of the C shell and also enhancing the
      user interaction of the Bourne Shell.
Applications/Application Programs: The last layer of the
Unix architecture is the Application Program layer. As
the name suggests, this outermost layer of Unix
Architecture is responsible for executing the application
programs.
In Unix, files and processes are core concepts. Here's a
simple overview:
1. Files in Unix
     Everything in Unix is treated as a file: documents,
      directories, hardware devices, and even running
      processes (through /proc).
     Files are organized in a single hierarchical directory
      structure (starting from /, the root).
Types of Files:
     Regular files: text files, images, binaries, etc.
     Directories: folders that contain other files.
     Special files:
        o   Character device files (e.g., keyboard input)
        o   Block device files (e.g., hard drives)
     Links:
        o   Hard links: multiple directory entries point to
            the same inode.
        o   Symbolic links (symlinks): like shortcuts.
     Sockets and named pipes: used for inter-process
      communication (IPC).
Important file commands:
     ls — list files
     cat, less, more — view contents
     cp, mv, rm — copy, move, remove
     chmod, chown — change permissions and
      ownership
2. Processes in Unix
     A process is an instance of a running program.
     Each process has a unique Process ID (PID).
     Processes can spawn child processes (parent and
      child relationship).
States of a Process:
     Running: currently executing.
     Sleeping: waiting for some event (like input).
     Stopped: process is halted.
     Zombie: completed execution but still has an entry
      in the process table.
Important process commands:
     ps — view currently running processes.
     top — dynamic real-time view of system processes.
     kill PID — send a signal to a process (default is
      SIGTERM to terminate).
     kill -9 PID — forcefully kill a process (SIGKILL).
     nice, renice — change the priority of a process.
     bg, fg, jobs — manage background and foreground
      jobs.
SYSTEM CALLS
The interface between a process and an operating
system is provided by system calls. In general, system
calls are available as assembly language instructions.
They are also included in the manuals used by the
assembly level programmers.
Unix System Calls
System calls in Unix are used for file system control,
process control, interprocess communication etc.
Access to the Unix kernel is only available through
these system calls. Generally, system calls are similar
to function calls, the only difference is that they remove
the control from the user process.
There are around 80 system calls in the Unix interface
currently. Details about some of the important ones are
given as follows -
 System
                Description
 Call
Features of unix
1. Multiuser System
     Many users can work at the same time.
     Resources (CPU, memory) are shared fairly.
2. Multitasking System
     One user can run many tasks together.
     Switch between tasks or run them in the
      background.
3. Building-Block Approach
     Small, simple commands that do one job well.
     Commands can be combined using pipes (|).
4. UNIX Toolkit
     Collection of powerful tools: text editors, compilers,
      network programs, admin tools.
5. Pattern Matching
     Special symbols (*, ?) to match file names.
     Regular expressions for advanced search.
6. Programming Facility
     Shell is both a command interpreter and a
      programming language.
    You can write shell scripts to automate tasks.
7. Documentation
    man command gives help on any command.
    Tons of resources and FAQs available online.
8. Portable
    Easily runs on different types of hardware.
9. Command-Line Interface (CLI)
    Powerful text-based control through shells (like
     bash, sh).
10. File System
    Organized in a hierarchical (tree-like) structure,
     starting from / (root).
11. Networking
    Built-in strong support for networking (great for
     servers).
12. Security
    Strong security with permissions and access
     controls.
13. Open Source
    Many UNIX versions are open-source and freely
     available.
14. Scalable
    Can work on small devices and huge data centers.
POSIX
What is POSIX?
POSIX stands for Portable Operating System
Interface.
It is not an operating system itself — it's a
standard.
POSIX defines rules and guidelines for how an
operating system (like UNIX) should behave so
that programs written for one system can work
on others without needing major changes.
In Short:
👉 POSIX = Set of rules that make sure UNIX-like
systems behave similarly, helping software run
across different platforms.
SINGLE UNIX SPECIFICATIONS
What is the Single UNIX Specification
(SUS)?
The Single UNIX Specification (SUS) is a
standard that defines what it means to be a
"real" UNIX operating system.
It is based on POSIX, but is broader and
stricter.
It ensures that software can run across
different UNIX systems without needing to be
rewritten.
In Short:
👉 SUS = The official standard that defines what
UNIX really is.
👉 POSIX = A part of SUS focused on portability.
INTERNAL AND EXTERNAL COMMANDS
Internal vs External Commands in UNIX
Internal Commands
    These are built into the shell itself (like
     bash, sh).
    When you run them, the shell executes
     them directly — no separate file is
     needed.
    They are faster because no separate process
     is created.
    Examples:
       o   cd — change directory
       o   pwd — print working directory
       o   echo — display text
       o   exit — close the shell
       o   set, unset, export — environment control
➡ Internal commands = Part of the shell
program itself.
External Commands
    These are separate executable files stored
     on disk.
    When you run them, the shell finds and
     starts a new process to execute them.
    They are usually located in system directories
     like /bin, /usr/bin, /usr/local/bin.
    Examples:
      o   ls — list files
      o   cp — copy files
      o   mv — move files
      o   cat — view file contents
      o   grep — search text
      o   chmod — change file permissions
➡ External commands = Separate files
stored outside the shell.
How to Check?
    Internal: Use help <command> → if it shows
     help, it's internal.
     External: Use which <command> → if it
      shows a file path, it's external.
Example:
$ help cd   # shows help → internal
$ which ls # shows /bin/ls → external
In Short:
👉 Internal = Built into shell, fast.
👉 External = Separate program, starts a new
process.
UTILITIES OF UNIX
The image you shared lists some important
UNIX utilities. Here's a clean and simple
version for you:
In Short:
These are simple command-line tools that
make system tasks easy!
Types of File:
The UNIX files system contains several different
types of files
Ordinary Files
An ordinary file is a file on the system that
contains data, text, or program instructions.
     Used to store your information, such as some
      text you have written or an image you have
      drawn. This is the type of file that you usually
      work with.
     Always located within/under a directory file.
     Do not contain other files.
     In long-format output of ls -l, this type of file
      is specified by the “-” symbol.
Directories
Directories store both special and ordinary files.
For users familiar with Windows or Mac OS, UNIX
directories are equivalent to folders. A directory
file contains an entry for every file and
subdirectory that it houses. If you have 10 files in
a directory, there will be 10 entries in the
directory. Each entry has two components. (1)
The Filename (2) A unique identification number
for the file or directory (called the inode number)
     Branching points in the hierarchical tree.
     Used to organize groups of files.
     May contain ordinary files, special files or
      other directories.
     Never contain “real” information which you
      would work with (such as text). Basically, just
      used for organizing files.
     All files are descendants of the root directory,
      ( named / ) located at the top of the tree.
In long-format output of ls –l , this type of file is
specified by the “d” symbol.
Special Files
Used to represent a real physical device such as
a printer, tape drive or terminal, used for
Input/Output (I/O) operations. Device or special
files are used for device Input/Output(I/O) on
UNIX and Linux systems. They appear in a file
system just like an ordinary file or a directory. On
UNIX systems there are two flavors of special
files for each device, character special files and
block special files :
     When a character special file is used for
      device Input/Output(I/O), data is transferred
      one character at a time. This type of access
      is called raw device access.
     When a block special file is used for device
      Input/Output(I/O), data is transferred in large
      fixed-size blocks. This type of access is called
      block device access.
For terminal devices, it’s one character at a time.
For disk devices though, raw access means
reading or writing in whole chunks of data –
blocks, which are native to your disk.
     In long-format output of ls -l, character
      special files are marked by the “c” symbol.
     In long-format output of ls -l, block special
      files are marked by the “b” symbol.
Pipes
UNIX allows you to link commands together using
a pipe. The pipe acts a temporary file which only
exists to hold data from one command until it is
read by another.A Unix pipe provides a one-way
flow of data.The output or result of the first
command sequence is used as the input to the
second command sequence. To make a pipe, put
a vertical bar (|) on the command line between
two commands.For example: who | wc -l In long-
format output of ls –l , named pipes are marked
by the “p” symbol.
Sockets
A Unix socket (or Inter-process communication
socket) is a special file which allows for advanced
inter-process communication. A Unix Socket is
used in a client-server application framework. In
essence, it is a stream of data, very similar to
network stream (and network sockets), but all the
transactions are local to the filesystem. In long-
format output of ls -l, Unix sockets are marked by
“s” symbol.
Symbolic Link
Symbolic link is used for referencing some other
file of the file system.Symbolic link is also known
as Soft link. It contains a text form of the path to
the file it references. To an end user, symbolic
link will appear to have its own name, but when
you try reading or writing data to this file, it will
instead reference these operations to the file it
points to. If we delete the soft link itself , the data
file would still be there.If we delete the source file
or move it to a different location, symbolic file
will not function properly. In long-format output of
ls –l , Symbolic link are marked by the “l” symbol
(that’s a lower case L).
File Naming Conventions:
Here are the file naming conventions in Unix:
1. Case Sensitivity
    File names in Unix are case-sensitive.
      o   Example: File.txt, file.txt, and FILE.TXT
          are all different files.
2. No Extension Requirement
    Unix does not require file extensions,
     though they are often used for convenience.
      o   Example: A shell script can be named
          script, script.sh, or even myscript.
3. Allowed Characters
    Most characters are allowed, except the
     forward slash / (used as a directory
     separator) and the null character (\0).
      o   Avoid using special characters like *, ?, |,
          <, >, &, etc., as they have special
          meanings in the shell.
4. Hidden Files
    Files beginning with a dot (.) are hidden
     files.
      o   Example: .bashrc, .gitignore
5. Length Limits
    File names can be up to 255 characters
     long (varies by file system).
    Full path length is typically limited to 4096
     characters.
🔧 How It Works:
 1.Process Creation via fork():
       o   In UNIX, when a process wants to create
           another process, it uses the fork() system
           call.
       o   The original process is called the parent.
         o   The newly created process is the child.
  2.Child Process:
         o   The child is a copy of the parent at the
             time of creation (same code, data, and
             open files).
         o   It gets a unique process ID (PID).
         o   It may be programmed to replace itself
             with a different executable using exec().
  3.Process IDs:
         o   Each process has:
                  PID – its unique identifier.
                  PPID – parent process ID.
  4.Tracking:
         o   The shell (like Bash) acts as a parent to the
             commands you run.
         o   Use ps -ef or pstree to see relationships
🧩 Key Points:
Concept             Description
fork()              Creates a new child process
                    Replaces current process image with
exec()
                    a new one
getpid()            Returns current process ID
getppid()           Returns parent process ID
Concept       Description
wait() /
              Parent waits for child to finish
waitpid()
Home Variable
In UNIX and Linux systems, the HOME environment
variable represents the path to the current
user's home directory.
📌 Purpose of HOME:
    Stores the default directory where a user is
     taken after logging in.
    It is used by many applications and scripts as
     the default location for personal files and
     configuration settings.
     Commands like cd without arguments use
      $HOME.
Common Use Cases:
Command        Description
               Takes you to the home directory
cd
               (same as cd $HOME)
cd ~           Shortcut to go to the home directory
echo $HOME Displays the home directory path
cp file.txt
               Copies file.txt to your home directory
$HOME/
Inode Number
What is an inode?
An inode is a file data structure that stores
information about any Linux file except its name
and data.
What are inodes used for?
Data is stored on your disk in the form of fixed-size
blocks. If you save a file that exceeds a standard
block, your computer will find the next available
segment on which to store the rest of your file.
Over time, that can get super confusing.
That’s where inodes come in. While they don’t
contain any of the file’s actual data, it stores the
file’s metadata, including all the storage blocks on
which the file’s data can be found.
Information contained in an inode:
     File size
     Device on which the file is stored
     User and group IDs associated with the file
     Permissions needed to access the file
     Creation, read, and write timestamps
     Location of the data (though not the filepath)
Inodes are also independent of filenames. That
means you can copy a single file, rename it, and
still have it point to the same inode as the original.
Absolute and Relative Path
In Unix and Linux systems, paths define the
location of files and directories within the
filesystem. They are crucial for navigating and
managing files efficiently. Paths can be classified
into two types: absolute paths and relative
paths. Let us have a better look in these paths.
What is an Absolute Path?
An absolute path is a full path that specifies the
location of a file or directory from the root directory
(‘/’). It provides a complete address that points
directly to a file or directory, regardless of the
current working directory. This path type always
begins with the root directory, followed by
subdirectories, and ends with the desired file or
directory name.
Characteristics of Absolute Paths:
     Starts with a slash (/).
     Specifies a file location from the root directory.
     Does not depend on the current directory.
For Example:
If you want to access a file named ‘abc.sql’ located
in the directory ‘/home/kt’, you would use the
following command:
$cat abc.sql
This command will work only if the
file “abc.sql” exists in your current directory.
However, if this file is not present in your working
directory and is present somewhere else say in
/home/kt , then this command will work only if you
will use it like shown below:
cat /home/kt/abc.sql
In the above example, if the first character of a
pathname is ‘/’, the file’s location must be
determined with respect to root. When you have
more than one / in a pathname, for each such /,
you have to descend one level in the file system
like in the above ‘kt’ is one level below home, and
thus two levels below root.
What is a Relative Path?
A relative path specifies the location of a file or
directory in relation to the current working
directory (often abbreviated as pwd). It does not
start with a slash (‘/’), and it utilizes navigational
shortcuts to refer to the file or directory.
Characteristics of Relative Paths:
     Does not begin with a slash (‘/’).
     Dependent on the current directory.
     Utilizes shortcuts like ‘.’ (current directory) and
      ‘..’ (parent directory) to navigate the
      filesystem.
Using . and .. in Relative Path-names
UNIX offers a shortcut in the relative pathname–
that uses either the current or parent directory as
reference and specifies the path relative to it. A
relative path-name uses one of these cryptic
symbols:
     . (Dot): Represents the current directory.
     .. (Double Dots): Represents the parent
      directory.
Now, what this actually means is that if we are
currently in directory ‘/home/kt/abc’ and now you
can use ‘..’ as an argument to ‘cd’ to move to the
parent directory /home/kt as :
$pwd
/home/kt/abc
$cd ..           ***moves one level up***
$pwd
/home/kt
Note: Now ‘/ ‘ when used with ‘..’ has a different
meaning; instead of moving down a level, it moves
one level up:
$pwd
/home/kt/abc        ***moves two level up***
$cd ../..
$pwd
/home
Example of Absolute and Relative Path
Suppose you are currently located in ‘home/kt’ and
you want to change your directory to
‘home/kt/abc’. Let’s see both the absolute and
relative path concepts to do this:
1. Changing directory with relative path
concept:
$pwd
/home/kt
$cd abc
$pwd
/home/kt/abc
2. Changing directory with absolute path
concept:
$pwd
/home/kt
$cd /home/kt/abc
$pwd
/home/kt/abc
Significanceof dot(.)anddotdot(..)
In computing, particularly in Unix-like operating
systems, a dot (.) refers to the current directory
and dotdot (..) refers to the parent
directory.27 These entries are automatically
created in every directory except the root
directory, and they are used to navigate the file
system.27 For example, if your directory
is /Users/Bob, then . refers
to /Users/Bob and .. refers to /Users.2
In programming, these special directories are often
not included in directory listings when they are not
needed for the specific task at hand. This can be
achieved by including QDir::NoDotAndDotDot in
the filter.2
The use of dot and dotdot is universal in
programming and computers in general.2
In file systems like FAT and NTFS, dot and dotdot
entries are created for every non-root directory,
although the exFAT specification does not provide
for them, Microsoft's implementation of exFAT still
returns these entries when listing non-root
directories.23
In summary, dot and dotdot are special directory
entries used for navigation and are present in most
file systems and directory structures.
Displaying pathname of the
current directory (pwd)
The ‘pwd,’ which stands for “print working
directory.” In this article, we will delve into the
‘pwd’ command, exploring its functionality, usage,
and various examples. It prints the path of the
working directory, starting from the root. pwd is
shell built-in command(pwd) or an actual
binary(/bin/pwd). $PWD is an environment
variable that stores the path of the current
directory. This command has two flags.
Syntax of `pwd` command in Linux
The basic syntax of the ‘pwd’ command is
pwd [OPTIONS]
This command doesn’t have any arguments or
options, but it can accept flags for specific
behavior.
Flags For Specific behavior in `pwd`
command in Linux.
     The “-L” flag resolves symbolic links and prints
      the path of the target directory.
     The default behavior of the shell built-in “pwd”
      is equivalent to using “pwd -L”.
     Mention the “-P” flag, which displays the actual
      path without resolving symbolic links.
     The default behavior of the binary “/bin/pwd” is
      the same as using “pwd -P”
pwd -L: Prints the symbolic path.
pwd -P: Prints the actual path.
How to Display the Current Working Directory
in Linux
1. Displaying the Current Working Directory
Using Built-in pwd (pwd):
To print the current working directory, simply enter:
$PWD
Executing this command prints the symbolic path
stored in the $PWD environment variable
Changing the current
directory(cd)
Cd is the abbreviation or synonym for chdir. It is a
command found inside the Windows Command
Processor (cmd) that allows for change of the
current working directory of a shell instance. The
CWD (Current Working Directory) is a path (of a
directory) inside the file system, where the shell is
currently working. The current working directory is
essential for resolving relative paths. Cd is a
generic command found in the Command
Interpreter of most operating systems.
Description of the Command :
Displays the name of or changes the current
directory.
CHDIR [/D] [drive:][path]
CHDIR [..]
CD [/D] [drive:][path]
CD [..]
Make directory(mkdir)
To create a directory in Linux or Unix, you can use
the mkdir command followed by the name of the
directory you want to create. For example, to
create a new directory called newdir, you would
run the following command:
mkdir newdir
You can also create multiple directories at once by
specifying their names as arguments separated by
spaces. For instance:
mkdir dir1 dir2 dir3
To create a directory and its parent directories if
they do not exist, use the -p option:
mkdir -p
Music/{Jazz/Blues,Folk,Disco,Rock/{Gothic,Punk,Pro
gressive},Classical/Baroque/Early}
To set specific permissions for the new directory,
use the -m option followed by the desired
permissions. For example, to create a directory
with 700 permissions, which means only the user
who created the directory can access it, you would
run:
mkdir -m 700 newdir
When the -m option is not used, the newly created
directories usually have either 775 or 755
permissions, depending on the umask value.
To display a message for each created directory,
use the -v option:
mkdir -v newdir
Remove directories(rmdir)
To remove directories in Linux, you can use
the rmdir and rm commands. The rmdir command
is used to remove empty directories only. If you
need to remove a non-empty directory, you should
use the rm command with the -r option, which
stands for recursive deletion.15
The rmdir command syntax is simple and does not
require additional options for empty directories.
However, if you want to remove a directory and its
parent directories if they are empty, you can use
the -p option.1
For the rm command, the -r option is used to
remove directories and their contents recursively.
The -f option forces the removal without prompting
for confirmation, and the -i option prompts for
confirmation before each removal.15
In Windows, the rmdir or rd command is used to
remove directories. To remove a directory tree,
including subdirectories and files, you can use
the /s option. The /q option specifies quiet mode,
which does not prompt for confirmation when
deleting a directory tree.2
It's important to be cautious when using these
commands, as they permanently remove
directories and files without moving them to a
trash or recycle bin.5
     rmdir: Removes empty directories only.
     rm: Removes files and directories, including
      non-empty directories with the -r option.
🔹 1. Displaying a File
To display the contents of a file in the terminal:
cat filename.txt
✅ This shows the content of filename.txt on the
screen.
🔹 2. Creating a File
You can use cat to create a new file:
cat > newfile.txt
Then type the content you want to include. Press
CTRL + D to save and exit.
Example:
cat > hello.txt
This is a new file.
CTRL + D
🔹 3. Appending to a File
To append new content to an existing file:
cat >> existingfile.txt
Type your new content, and press CTRL + D when
done.
🔹 Tips
     Use cat -n filename.txt to display line
      numbers.
     Use cat with more or less for long files: cat
      filename.txt | less.
🔹 Basic Syntax
cp [options] source destination
✅ Examples
1. Copy a File
cp file1.txt file2.txt
This copies file1.txt to a new file named file2.txt.
If file2.txt already exists, it will be overwritten
without warning (unless options are used).
🔹 Common Options
Optio
      Description
n
-i     Prompt before overwrite
-r     Copy directories recursively
-v     Verbose (show files being
Optio
      Description
n
       copied)
-u     Copy only if source is newer
Deleting a file(rm)
In UNIX, the rm command is used to delete
(remove) files and directories.
🔹 Basic Syntax
rm [options] filename
✅ Examples
1. Delete a File
rm file.txt
This removes file.txt permanently — no recycle
bin!
⚠️Be Careful!
     rm does not move files to trash — once
      deleted, recovery is difficult.
     Always double-check file names, especially
      with -f or -r.
Renaming / moving a file(mv)
In UNIX, the mv command is used to rename or
move files and directories.
🔹 Basic Syntax
mv [options] source destination
✅ Examples
1. Rename a File
mv oldname.txt newname.txt
This renames oldname.txt to newname.txt.
5. Verbose Output
mv -v file1.txt file2.txt
Shows what’s being moved or renamed.
🔹 Common Options
Optio
      Description
n
-i         Prompt before overwriting
-f         Force move, no prompt
           Verbose (show what's
-v
           happening)
⚠️Notes:
        If the destination is a file that already
         exists, mv will overwrite it without warning,
         unless you use -i.
        mv can both move and rename in one
         step.
🔹 Basic Syntax
more filename
This displays the contents of filename page-by-
page.
✅ Examples
1. Read a Long File
more longfile.txt
Shows the file one screen at a time. Press:
     Space → Next page
     Enter → Next line
     q → Quit
     /pattern → Search forward for a pattern
🔄 Comparison Tip
       more is older and simpler.
       less is more powerful (can scroll up/down
        freely).
Example using less:
less filename
Printing a file(lp)
In UNIX, the lp command is used to send files to
a printer — it's part of the CUPS (Common
UNIX Printing System) used in many modern
UNIX and Linux systems.
🔹 Basic Syntax
lp [options] filename
✅ Examples
1. Print a File
lp document.txt
This sends document.txt to the default printer.
🔹 Common lp Options
Optio
      Description
n
-d       Specify printer name
-n       Number of copies
-t       Job title
         Set options (e.g., media
-o
         size)
         Connect to a remote print
-h
         server
🔹 Basic Syntax
file filename
✅ Examples
1. Check Type of a File
file notes.txt
Output might be:
notes.txt: ASCII text
Line
In UNIX file handling, a "line" refers to a
sequence of characters ending with a newline
character (\n), and it is a fundamental unit when
reading, writing, or processing files. Here's how
lines are handled in various file operations:
🔹 Basic Syntax
wc [options] filename
✅ Common Examples
1. Count Lines, Words, and Characters
wc filename.txt
Example output:
10 25 120 filename.txt
This means:
     10 → Lines
     25 → Words
     120 → Characters (or bytes)
     filename.txt → File name
2. Count Only Lines
wc -l filename.txt
3. Count Only Words
wc -w filename.txt
4. Count Only Characters
wc -m filename.txt
5. Count Bytes (instead of characters)
wc -c filename.txt
(Useful for binary files where byte count ≠
character count)
🔹 Summary of wc Options
Optio
      Meaning
n
-l    Count lines
-w    Count words
-m    Count
Optio
      Meaning
n
           characters
-c         Count bytes
🔹 Basic Syntax
cmp [options] file1 file2
✅ Common Examples
1. Compare Two Files
cmp file1.txt file2.txt
        If files are identical, there is no output.
        If files differ, cmp shows the byte and line
         number of the first difference.
Example Output:
file1.txt file2.txt differ: byte 12, line 3
🔹 Exit Codes
Exit
               Meaning
Code
               Files are
0
               identical
1              Files differ
2              Error occurred
🔄 Related Commands
Comman
       Purpose
d
          Line-by-line differences
diff
          (text)
cmp       Byte-by-byte comparison
          Compare sorted files line-
comm
          by-line
📌 Example
file1.txt
apple
banana
cherry
file2.txt
banana
cherry
date
🔸 Run:
sort file1.txt -o file1.txt
sort file2.txt -o file2.txt
comm -12 file1.txt file2.txt
✅ Output:
banana
cherry
🔹 Summary
Command                   Description
comm file1.txt            Compare two sorted
file2.txt                 files
comm -12 file1.txt        Show common lines
file2.txt                 only
comm -23 file1.txt
                          Lines only in file1
file2.txt
comm -13 file1.txt
                          Lines only in file2
file2.txt
✅ Example Files
file1.txt:
apple
banana
cherry
file2.txt:
apple
banana
date
🔸 Run:
diff file1.txt file2.txt
🔸 Output:
3c3
< cherry
---
> date
🔍 Explanation:
     3c3 → line 3 changed in both files
     < cherry → line in file1.txt
     > date → line in file2.txt
🔹 Common diff Options
Option                  Description
-y                      Side-by-side comparison
                        Context format (adds
-c
                        surrounding lines)
                        Unified format (compact,
-u
                        preferred for code diffs)
--suppress-             Hide lines that are the same
common-lines            when using -y
🔸 Side-by-Side Comparison
diff -y file1.txt file2.txt
Output:
apple           apple
banana           banana
cherry     | date
🔹 Summary
Task                    Command
Basic comparison        diff file1 file2
Unified diff (e.g., for diff -u file1
Git)                    file2
                        diff -y file1
Side-by-side view
                        file2
🔹 Basic Syntax
tar [options] archive_name.tar files/directories
✅ Creating an Archive
tar -cvf archive.tar file1.txt file2.txt folder/
Breakdown:
     -c → Create a new archive
     -v → Verbose (list files being archived)
     -f → Use the specified archive file name
     archive.tar → Output archive file
     file1.txt, folder/ → Files/folders to include
📝 Examples
🔸 Create an archive of a folder:
tar -cvf backup.tar myfolder/
🔸 Create and compress with gzip:
tar -czvf backup.tar.gz myfolder/
🔸 Extract an archive:
tar -xvf backup.tar
🔸 Extract a .tar.gz file:
tar -xzvf backup.tar.gz
Compress file(gzip)
In UNIX, the gzip command is used to compress
files using the GNU zip algorithm, reducing file
size and saving disk space. It creates files with
a .gz extension.
🔹 Basic Syntax
gzip [options] filename
✅ Examples
🔸 Compress a Single File
gzip myfile.txt
     This replaces myfile.txt with a compressed
      file: myfile.txt.gz
Uncompress file(gunzip)
In UNIX, the gunzip command is used to
uncompress files that were compressed using
the gzip command. These files typically have
a .gz extension.
🔹 Basic Syntax
gunzip [options] filename.gz
🔹 Summary
Command           Action
                  Uncompress and remove
gunzip file.gz
                  .gz
gzip -d file.gz   Same as gunzip
gzip -dc file.gz > Uncompress but
file               keep .gz file
✅ Examples
🔸 Create a ZIP Archive
zip myarchive.zip file1.txt file2.txt
     Creates myarchive.zip containing file1.txt
      and file2.txt.
🔹 Basic Syntax
unzip archive.zip
     Extracts all files from archive.zip into the
      current directory.
✅ Common Examples
🔸 Extract ZIP Archive
unzip myarchive.zip
     Extracts contents into the current folder.
🔹 Summary Table
Comman
       Directory Action            Notes
d
           Requires -r to copy     Without -r, will
cp
           directory recursively   error out
                                 -rf for forced
           Requires -r to remove
rm                               recursive
           directory recursively
                                 deletion
           Moves or renames        Moves entire
mv         directories without     directory and
           extra flags             contents
MODULE-4 FILE
ATTRIBUTES
File and directory attributes
listing and very brief idea about
the attributes
Each file has characteristics like file name, file
type, date (on which file was created), etc. These
characteristics are referred to as 'File
Attributes'. The operating system associates
these attributes with files. In different operating
systems files may have different attributes. Some
people call attributes metadata also.
Following are some common file attributes:
  1.Name: File name is the name given to the
    file. A name is usually a string of characters.
  2.Identifier: Identifier is a unique number for
    a file. It identifies files within the file system.
    It is not readable to us, unlike file names.
  3.Type: Type is another attribute of a file which
    specifies the type of file such as archive file
    (.zip), source code file (.c, .java), .docx
    file, .txt file, etc.
  4.Location: Specifies the location of the file on
    the device (The directory path). This attribute
    is a pointer to a device.
  5.Size: Specifies the current size of the file (in
    Kb, Mb, Gb, etc.) and possibly the maximum
    allowed size of the file.
  6.Protection: Specifies information about
    Access control (Permissions about Who can
    read, edit, write, and execute the file.) It
    provides security to sensitive and private
    information.
  7.Time, date, and user identification: This
    information tells us about the date and time
    on which the file was created, last modified,
    created and modified by which user, etc.
OS File Attributes
Some Other Attributes May Include:
Attributes related to flags. These Flags
control or enable some specific property:
 1.Read-only flag: 0 for read/write; 1 for read-
   only.
 2.Hidden flag: 0 for normal; 1 for do not
   display in listings of all files.
 3.System flag: 0 for normal files; 1 for system
   files.
 4.Archive flag: 0 for has been backed up; 1
   for needs to be backed up.
 5.ASCII/binary flag: 0 for ASCII file; 1 for
   binary file.
 6.Random access flag: 0 for sequential
   access only; 1 for random access.
 7.Temporary flag: 0 for normal; 1 for deleted
   file on process exit.
 8.Lock flags: 0 for unlocked; nonzero for
   locked.
Attribute related to keys. These are present
in files which can be accessed using key:
 1.Record length: Number of bytes in a record.
 2.Key position: Offset of the key within each
   record.
 3.Key length: Number of bytes in the key
   field.
Some file systems also support extended file
attributes, such as character encoding of the
file and security features such as a file
checksum.
All above attributes are not present in all files.
Files may posses different attributes as per the
requirement. The attributes also varies from
system to system. Attributes are also stored in
secondary storage (File name and identifier are
stored in directory structure. Identifier in turn
locates other attributes). Attributes are important
because they provide that extra information
about the files which can be useful.
File ownership
In UNIX, every file and directory has an owner
and a group. File ownership is a key part of the
UNIX permissions system, which helps control
who can read, write, or execute files.
🔧 Changing Ownership
✅ Change File Owner
sudo chown newuser file.txt
     Changes owner of file.txt to newuser
✅ Change Owner and Group
sudo chown newuser:newgroup file.txt
     Changes owner to newuser and group to
      newgroup
🔹 Summary Table
Command             Purpose
ls -l               View file ownership
chown user file Change file owner
chown               Change owner and
user:group          group
chgrp group         Change group
file                ownership
File permissions
Here’s a summary of file ownership and
permissions in UNIX:
🔐 File Ownership
Each file in UNIX has:
     Owner: Creator of the file
     Group: Users with shared access
     Others: Everyone else
📄 File Permissions
Permissions define who can do what with a file or
directory:
     Read (r): View contents
     Write (w): Modify or delete
     Execute (x): Run (for files) / Enter (for
      directories)
Permissions are shown with ls -l:
-rwxr-xr-- 1 owner group ...
     1st character: Type (- for file, d for directory)
     Next 9 characters: Permissions for owner,
      group, and others (in sets of 3)
Changing Permissions – chmod
Symbolic Mode:
    + → Add permission
    - → Remove permission
    = → Set exact permission
Examples:
chmod u+x file          # Add execute for owner
chmod g=rx file         # Set group to read and
execute
chmod o-wx file         # Remove write/execute from
others
Absolute (Octal) Mode:
Permissions represented numerically:
Permissi Valu Symb
on       e    ol
None       0      ---
Execute    1      --x
Write      2      -w-
Read       4      r--
Examples:
chmod 755 file          # rwx for owner, rx for group
and others
chmod 644 file       # rw for owner, r for group and
others
👥 Changing Ownership
chown – Change file owner:
chown user file
chgrp – Change file group:
chgrp group file
     Only root can change ownership of others'
      files.
     Users can change group ownership if they
      belong to that group.
📁 Directory Permissions
     Read: List files
     Write: Add or delete files
     Execute: Enter the directory (cd) or access
      its contents
✅ Important Notes:
    Only the superuser (root) can change file
     owner.
    Owners can change the group only to one
     they belong to.
    Use ls -l to verify changes.
🔍 View Ownership:
ls -l filename
Example Output:
-rw-r--r-- 1 alice developers 1234 May 15 10:00
report.txt
⚠️Important Points:
     You must be either:
        o   The file owner, and a member of the new
            group.
        o   Or the superuser (root).
     If you're not part of the target group, you
      can’t assign it.
Here's a well-organized and easy-to-understand
note on File System and Inodes in UNIX –
great for study or technical documentation.
🔸 Inode Contains:
     File type (regular, directory, link)
     Permissions (rwx)
     Owner UID
     Group GID
     Size of the file
     Timestamps (created, modified, accessed)
     Link count (how many names point to this
      file)
     Pointers to disk blocks (where file data is
      stored)
⚠️Inode Notes:
     Each file has only one inode, but many
      filenames (hard links) can point to it.
     If you delete a filename, the file isn't
      removed until all hard links (and open file
      descriptors) are gone.
     Inodes are finite. If you run out of inodes, you
      cannot create new files—even if disk space is
      available.
🔧 Check inode usage on disk:
df -i
🧠 Summary
Term          Description
File          Organizes files and directories
System        on disk
              Data structure with metadata
Inode
              for a file
Link          Filename pointing to an inode
ls -i         Shows inode number
stat          Shows full inode info
 Hard Link
🔹 What is a Hard Link?
A hard link is a direct reference to the inode of a
file. Multiple hard links can point to the same
inode, meaning they all share the same data and
metadata (except the file name).
🧠 Summary Table
Feature           Soft Link
Links to          File name (path)
Shared inode      No
Affected by       Breaks if original file is
deletion          deleted
Cross-file system
                  Yes
link
Works on
                  Yes
directories
Command to
                  ln -s source target
create
📝 Summary:
    Read permission lets you see filenames
     inside the directory (e.g., ls command).
    Write permission lets you modify the
     directory contents (create/delete files).
    Execute permission lets you access the files
     or subdirectories inside the directory and
     traverse it.
Example:
    If a user has read but not execute
     permission on a directory, they can see the
     file names but cannot access or open them.
    If a user has execute but not read
     permission, they cannot list the files but can
     access files if they know the exact filename.
2. What is umask?
    umask (user file creation mask) determines
     which permission bits will be disabled
     (masked off) when a new file or directory is
     created.
    It subtracts permissions from the system
     defaults.
4. Example of umask
                                    Final
umas           Final File Effect on
      Effect                        Directory
k              Permissi Directorie
      on Files                      Permissio
Value          on         s
                                    n
        removes
                              removes
        write for
                  644 (rw-r-- write for 755 (rwxr-
022     group
                  r--)        group and xr-x)
        and
                              others
        others
        removes
                              removes     775
        write for 664 (rw-
002                           write for   (rwxrwxr-
        others rw-r--)
                              others only x)
        only
        removes
                              removes
        all for
                600           all for   700
077     group
                (rw-------)   group and (rwx------)
        and
                              others
        others
6. Summary
            File    Directory
Aspect                        Effect of umask
            Default Default
System                            Masks out
default     666       777         permission bits
perms                             from defaults
Typical     022              Removes write
                    022
umask       (common          permission for
                    (common)
value       )                group and others
4. Summary
Comman
       Shows
d
              Modification time
ls -l
              (mtime)
ls -lu        Access time (atime)
ls -lc        Change time (ctime)
stat          Detailed timestamps
2. Basic Usage
     Update access and modification times to the
      current time:
     touch filename
2. Basic Syntax
find [path] [options] [expression]
     path: Directory where search begins (default
      is current directory .).
     options and expression: Criteria to match
      files/directories.
3. Common Examples
    Find files by name:
    find /home/user -name "file.txt"
    Find files by case-insensitive name:
    find /home/user -iname "File.TXT"
    Find all directories named docs:
    find / -type d -name "docs"
    Find all regular files with .log extension:
    find /var/log -type f -name "*.log"
    Find files modified in last 7 days:
    find /home/user -mtime -7
    Find files larger than 10MB:
    find / -size +10M
    Find files with specific permissions:
    find / -perm 644
MODULE-5 SHELL
INTERPRETIVE CYCLE OF SHELL
In UNIX, the shell is an interpreter that
processes commands entered by the user. The
interpretive cycle refers to the process the
shell follows to read, interpret, and execute
commands.
🧠 Summary
The interpretive cycle of the UNIX shell can
be summarized as:
Prompt → Read → Parse → Interpret →
Execute → Wait → Output → Repeat
This cycle continues as long as the user is
interacting with the shell.
TYPES OF SHELL
In UNIX and UNIX-like operating systems, a shell
is a command-line interpreter that provides a
user interface for accessing the system's
services. There are several types of shells, each
with its own features, syntax, and scripting
capabilities.
Pattern Matching
In the UNIX shell (like bash, sh, zsh), pattern
matching is called globbing. It is used mainly
for filename expansion and string matching
in shell scripts.
case "$filename" in
    *.pdf) echo "PDF file";;
    *.txt) echo "Text file";;
    *) echo "Unknown file type";;
esac
🧾 [[ ]] conditional with pattern
You can use pattern matching with [[ and ==:
file="data.csv"
if [[ $file == *.csv ]]; then
     echo "It's a CSV file"
fi
Use =~ for regex matching:
if [[ "hello123" =~ ^hello[0-9]+$ ]]; then
     echo "Pattern matched!"
fi
✅ Summary
Feature              Syntax Use
Wildcard             *, ?, [] File operations
Feature            Syntax Use
matching
                   case, [[ Conditional
Scripting match
                   ]]       execution
                              Pattern match with
Regex match        [[ =~ ]]
                              regex
🔸 Practical Examples
Escaping a wildcard:
touch file\*name.txt # Creates a file named
file*name.txt
Escaping a dollar sign:
echo "This is \$100" # Prints: This is $100
Escaping within commands:
grep "1\.0" file.txt # Match "1.0" literally (dot is
a special character in regex)
✅ Summary
Metho                               Substitution
      Description
d                                   Allowed?
        Escapes the next
\                                   No
        character
        Strong quoting –
'...'                               No
        everything literal
        Weak quoting – protects
"..."                               Yes
        most, but allows $, `
Quoting
Quoting in the UNIX shell is used to control
how the shell interprets special characters
like spaces, $, *, |, and more. It helps avoid
unintended behavior in commands and scripts.
Example in Script
#!/bin/bash
name="John Doe"
echo "Hello $name"     # Correct
echo Hello $name      # Will treat "John" and
"Doe" as separate arguments
📥📤 Types of Redirection
🔹 1. Standard Output Redirection (>)
Sends the output of a command to a file,
replacing its contents.
ls > file_list.txt
# Output of `ls` is written to file_list.txt
🔹 2. Append Output (>>)
Adds output to the end of a file, preserving
existing contents.
echo "New entry" >> log.txt
✅ Summary Table
Operat
       Purpose                 Example
or
>        Redirect stdout       ls > out.txt
Operat
       Purpose                   Example
or
>>          Append stdout        echo hi >> out.txt
<           Redirect stdin       sort < data.txt
2>          Redirect stderr      ls nofile 2> error.txt
            Merge stderr with    command > all.txt
2>&1
            stdout               2>&1
&>          Redirect both (bash) command &> all.txt
                                 See cat << EOF
<<          Here Document
                                 example
                                 grep "foo" <<<
<<<         Here String
                                 "foobar"
✅ Summary
Metho
      Description              Example
d
Keyboar
        Default stdin          read var
d
            Redirect file to
< file                         sort < input.txt
            stdin
`           `                  Pipe stdout → stdin
<<          Here Document cat << EOF
                               grep "x" <<<
<<<         Here String
                               "example text"
✅ Summary
               Symb
Operation           Description       Example
               ol
Output to      (defaul
                       Normal stdout echo "hi"
terminal       t)
               Symb
Operation           Description        Example
               ol
Redirect to           Overwrite file echo hi >
               >
file                  with output    out.txt
Append to             Add output to echo hi >>
               >>
file                  end of file   out.txt
Pipe to                                stdout to
another        `      `                next cmd’s
cmd                                    stdin
Explicit                               echo test 1>
               1>     stdout to file
descriptor                             out.txt
✅ Summary Table
Operato
        Description               Example
r
          Redirect stderr to a    ls nofile 2>
2>
          file                    errors.txt
          Redirect stderr to      command >
2>&1
          stdout                  all.txt 2>&1
&>        Redirect both stdout command &>
Operato
        Description               Example
r
           & stderr               all.txt
2>        Ignore error            command 2>
/dev/null messages                /dev/null
📌 Summary
                                    Common
Device Purpose           Behavior
                                    Use
         Discards                     Suppress
/dev/                    Data is lost
         everything                   unwanted
null                     (black hole)
         written to it                output
         Current user Connects to Prompt user
/dev/tty terminal     user’s      during
         device       terminal    redirected I/O
🔹 What is a Pipe?
     The pipe symbol: |
     It takes the standard output (stdout) of
      the command on the left and passes it
      as standard input (stdin) to the
      command on the right.
     Enables building command chains for
      complex tasks.
🔹 Basic Example
ls -l | grep ".txt"
     ls -l lists files.
     grep ".txt" filters output to show only .txt
      files.
✅ Summary
Symb Descripti
               Example
ol   on
                      Pipe stdout of one command to
`          `
                      stdin of next
🔹 Basic Syntax
command | tee filename
🔹 Examples
Write output to a file and display on
terminal
ls -l | tee filelist.txt
     Lists files.
     Shows output on screen.
     Saves output to filelist.txt.
✅ Summary
                                       Examp
Option      Description
                                       le
            Write stdout to file and
None                                   `cmd
            screen
            Append instead of
-a                                     `cmd
            overwrite
Multiple
            Write to multiple files    `cmd
files
🔹 Purpose
     Capture the output of a command and
      store it in a variable or use it directly.
     Helps automate scripts by dynamically
      generating values.
🔹 Syntax
Two common ways to do command substitution:
  1.Using backticks `command` (older style)
  2.Using $(command) (preferred modern style)
🔹 Examples
Using backticks
today=`date`
echo "Today's date is: $today"
Using $()
files_count=$(ls | wc -l)
echo "Number of files: $files_count"
🔹 Use in commands
echo "Home directory contains $(ls ~ | wc -l)
items."
✅ Summary
Syntax       Description              Example
`command Older command                today=`dat
`        substitution                 e`
$
         Modern, preferred
(command                              `files=$(ls
         syntax
)
Shell Variables
Shell variables store data or values that can be
used and manipulated within shell scripts or
command line sessions.
🔹 Types of Shell Variables
  1.User-defined variables — created by users
    or scripts.
  2.Environment variables — exported to child
    processes.
  3.Special variables — predefined by the shell
    (e.g., $?, $#).
🔹 Accessing Variables
Use $ before variable name to get its value.
echo "Name is $name"
echo "Age is $age"
🔹 Exporting Variables
To make variables available to child processes,
use export:
export PATH=$PATH:/my/custom/path
🔹 Special Variables
Variabl
        Meaning
e
$?        Exit status of last command
$$        PID of current shell process
$#        Number of arguments passed
$0        Name of the shell/script
$1,       Positional parameters (arguments to
$2, ...   scripts)
🔹 Tips
     Use quotes around variable values with
      spaces: var="Hello World"
    Use {} for clarity: ${var}
✅ Summary
Action           Syntax       Example
Assign                        name="Alic
                 var=value
variable                      e"
Access           $var or $    echo
variable         {var}        $name
Export                        export
                 export var
variable                      PATH
                 $?, $$, $#,
Special vars                 echo $?
                 $1
🔹 What is a Process?
    A process is an active program with its
     own:
       o   Process ID (PID)
      o   Memory space
      o   Program counter (current execution
          point)
      o   File descriptors (input/output)
      o   State (running, sleeping, stopped, etc.)
🔹 Process Lifecycle
 1.Created — when a program starts (using
   fork() and exec() system calls).
 2.Running — executing instructions on the
   CPU.
 3.Waiting — waiting for resources or
   input/output.
 4.Terminated — finished execution or killed.
🔹 Process States
State Description
Runnin
       Currently executing on CPU
g
Sleepin
        Waiting for an event or resource
g
Stoppe
       Suspended or paused
d
Zombie Finished but still has an entry in process
State Description
          table (waiting for parent to acknowledge)
🔹 Process Identification
     PID (Process ID): Unique identifier for each
      process.
     PPID (Parent Process ID): The PID of the
      process that started (created) this process.
🔹 Viewing Processes
     Use ps to see current processes.
     Use top or htop for dynamic process
      monitoring.
     Use kill to send signals to processes.
Example:
ps aux | grep firefox
🔹 Process Control
     Foreground process: Runs interactively;
      shell waits until it finishes.
     Background process: Runs concurrently;
      shell returns prompt immediately (run
      command with &).
sleep 30 & # Run sleep in background
🔹 Signals
     Processes can receive signals to perform
      actions:
       o   SIGTERM (terminate)
       o   SIGKILL (force kill)
       o   SIGSTOP (pause)
       o   SIGCONT (continue)
✅ Summary
Concept Description
              Running instance of a
Process
              program
PID           Unique process identifier
PPID          Parent process ID
Foregroun
          Runs with shell waiting
d
Backgrou
         Runs asynchronously
nd
              Control commands to
Signals
              processes
Displaying Process Attributes
Using ps Command
The ps command is used to view information
about running processes on your system. It
shows details (attributes) like process ID, user,
CPU usage, memory usage, command name, etc.
🔹 Basic Usage
ps
Shows processes running in the current shell
session.
✅ Summary
Comman
       Description
d
            Show current shell
ps
            processes
            Show all processes with
ps aux
            details
ps -ef      Full-format all processes
            Show info for specific
ps -p PID
            process
ps -eo      Customize displayed
cols        columns
Displaying System Processes
System processes are usually started by the
system or root user and run in the background to
manage system tasks.
2. Using ps aux
ps aux
     Shows all processes.
     The USER column shows process owner;
      system processes usually run as root or other
      system users.
Summary:
Command            Description
ps -ef             Show all processes
Command           Description
Flow Diagram:
Kernel boot
   ↓
init (PID 1)
   ↓
getty (terminal login prompt)
   ↓
login (user authentication)
   ↓
User’s Shell (command prompt)
Summary:
Ste
    Role
p
       Starts system services and
init
       terminals
gett
     Presents login prompt on terminal
y
logi Authenticates user and sets
n    environment
Ste
    Role
p
Shel Provides user interface for
l    commands
Additional Notes
       Processes can move between states, for
        example from Running → Sleeping → Running.
       Zombie processes are usually harmless but
        indicate that the parent process hasn't
        waited on the child.
       T (stopped) processes can be resumed with
        kill -CONT PID.
Summary Table
Cod                        Example
    Description
e                          Usage/Meaning
         Running or        Process currently using
R
         runnable          CPU or ready
         Sleeping          Waiting for input or
S
         (interruptible)   resource
         Uninterruptible   Waiting for I/O
D
         sleep             (disk/network)
         Stopped or        Suspended by signal (e.g.,
T
         traced            Ctrl+Z)
                           Defunct process, exited
Z        Zombie
                           but not reaped
Zombie State
A zombie process is a process that has
completed execution but still has an entry
in the process table. It’s also called a defunct
process.
Summary
Aspect        Description
State
              Z (Zombie / Defunct)
Code
              Process terminated but not
Meaning
              waited on
Consume
        No CPU/memory, holds PID
s
Solution Parent calls wait() to reap
Aspect    Description
Background Jobs
Background jobs let you run commands without
waiting for them to finish, so you can keep using
the shell prompt.
4. Example
# Run script in background
./backup.sh &
Summary
Command           Purpose
command &         Run command in background
nohup             Run command immune to
command &         hangup
jobs              List background jobs
fg %job / bg
                  Manage job state
%job
🔹 Example
nice -n 15 tar -czf backup.tar.gz /large/directory
     Compressing runs with low CPU priority, so
      other processes get preference.
Summary:
Command                 Purpose
nice -n <value>         Start command with given
command                 nice value
renice <value> -p       Change nice value of
<PID>                   running process
ps -o pid,ni,cmd        View niceness of processes
2. killall Command
Kills processes by name instead of PID.
killall firefox
     Sends SIGTERM by default.
     Use -9 for force kill.
3. pkill Command
Similar to killall but more flexible (pattern
matching).
pkill -9 sshd
Example
pid=$(pidof myprogram)
kill -15 $pid    # politely ask to terminate
sleep 5
kill -9 $pid    # force kill if still running
Summary
Command Usage
                Send termination signal to
kill <PID>
                process
Command Usage
kill -9
                Force kill process
<PID>
killall
                Kill process by name
<name>
pkill           Kill processes matching
<pattern>       pattern
3. List Jobs
jobs
Shows jobs with job numbers and states.
Summary
Comman
       Description
d
command
        Start command in background
&
Ctrl + Z    Stop (pause) running job
            Resume stopped job in
bg %job
            background
            Bring background job to
fg %job
            foreground
jobs        List current jobs
Useful Options
Optio
      Description
n
-l         List jobs with PIDs
           List only PIDs of the
-p
           jobs
Example:
jobs -l
Shows something like:
[1]+ 2345 Running          sleep 100 &
[2]- 2346 Stopped         vim file.txt
Summary
Comman
       Purpose
d
            List current shell
jobs
            jobs
jobs -l     List jobs with PIDs
jobs -p     List only job PIDs
Example Workflow
$ sleep 100
# Press Ctrl+Z
[1]+ Stopped             sleep 100
$ jobs
[1]+ Stopped             sleep 100
$ bg %1     # Resume in background
[1]+ sleep 100 &
Summary
               Command /
Action                   Effect
               Key
Suspend job Ctrl + Z       Stops the running job
List                       Show all
suspended      jobs        stopped/background
jobs                       jobs
               bg
Resume in                 Continue job in
               %job_numbe
background                background
               r
                Command /
Action                    Effect
                Key
                fg
Resume in                  Bring job to
                %job_numbe
foreground                 foreground
                r
Killing a Job
You can kill a job that’s running or stopped in
your current shell session by sending it a
termination signal.
Summary Table
Command            Description
                   List current shell
jobs
                   jobs
                   Kill job by job
kill %job_number
                   number
kill -9
                   Force kill job
%job_number
jobs -l            List jobs with PIDs
kill PID           Kill job by PID
2. batch Command
     Runs commands when system load is low
      (based on loadavg).
     Useful for scheduling jobs to run during idle
      times without specifying exact time.
Usage
batch
Then type the commands to run, and finish with
Ctrl+D.
Summary
Comman
       Purpose                     When It Runs
d
            Schedule job at        At the specified
at
            specific time          time
            Schedule job when      When system
batch
            system is idle         load is low
Summary
Command         Purpose
echo $VAR       Show value of variable
export
                Set variable (temporarily)
VAR=value
                List all environment
env, printenv
                variables
                Remove an environment
unset VAR
                variable
Variable Description
         The path to the current user's home
HOME
         directory.Example: /home/alice
         A colon-separated list of directories the
         shell searches for
PATH
         executables.Example:
         /usr/local/bin:/usr/bin:/bin
LOGNA    The login name of the current user
ME       (same as $USER in most cases).
         The username of the currently logged-
USER
         in user.
         Specifies the type of terminal to
TERM
         emulate (e.g., xterm, vt100).
         Present Working Directory — shows the
PWD
         current directory you’re in.
         Primary shell prompt string — defines
         how your command prompt looks.
PS1
         Default: usually \u@\h:\w\$
         (user@host:cwd$)
PS2      Secondary prompt — shown when a
         command is incomplete (e.g., waiting
Variable Description
           for more input).Default: >
🔹 Example Usage
echo $HOME       # Displays your home directory
echo $PATH # Shows all paths where shell
looks for commands
echo $PWD       # Shows your current working
directory
🔹 Modifying a Variable
export PATH=$PATH:/custom/bin # Add
/custom/bin to your PATH
export PS1=">> "              # Change shell
prompt
🔹 Tip
To permanently change an environment
variable, add the export line to your shell config
file:
     For bash: ~/.bashrc or ~/.bash_profile
     For zsh: ~/.zshrc
Aliases
Aliases in UNIX shell are shortcuts or custom
names for longer commands. They help you
save time, reduce typing, and avoid mistakes
with frequently used or complex commands.
🔹 Create an Alias
Temporary Alias (lasts for current shell
session):
alias name='command'
Example:
alias ll='ls -l'
alias gs='git status'
alias rm='rm -i'    # Prompts before deleting
🔹 Remove an Alias
unalias name
Example:
unalias ll
🔹 Notes
     Aliases do not accept arguments. For that,
      use a function.
     You can view the actual command behind an
      alias:
type ll
✅ Summary
Command              Purpose
alias
                     Create alias
name='cmd'
Command           Purpose
unalias name      Remove alias
alias             List all aliases
type              See what an alias
alias_name        maps to
🔹 Configuration
Where Is History Stored?
        Usually stored in ~/.bash_history (for Bash)
         or ~/.zsh_history (for Zsh).
        You can view or edit this file directly.
✅ Summary
Comman
       Description
d
               Show history of
history
               commands
!!             Repeat last command
               Run specific past
!n / !cmd
               command
Ctrl + R       Reverse search in
Comman
       Description
d
             history
             Clear the command
history -c
             history
🔹 Basic Syntax
pr [options] filename
🔹 Common pr Options
Option Description
-n       Add line numbers
-d       Double-space the output
-t       Remove headers and footers
-h "text" Set a custom header
         Set page length to N lines
-l N
         (default is 66)
Option Description
-o N      Set left margin offset to N spaces
          Set page width (for multicolumn
-w N
          output)
-      Format output into that many
COLUMN columns
🔹 Examples
1. Format file for printing:
pr myfile.txt
Adds headers with filename, date, and page
numbers.
✅ Summary
Command
                     Output
Example
head file.txt        First 10 lines
tail file.txt        Last 10 lines
                     Live output as file
tail -f file.txt
                     grows
`head -n 50          tail -n 10`
🔹 Syntax
cut [OPTION]... [FILE]
🔹 Common Options
Optio
      Description
n
-b     Select bytes
-c     Select characters
       Select fields
-f
       (columns)
       Set delimiter (used
-d
       with -f)
🔹 Examples
1. Cut by Byte Position
cut -b 1-5 file.txt
→ Prints first 5 bytes from each line.
✅ Summary
Use Case                     Command Example
First 5 bytes                cut -b 1-5 file.txt
First 10 characters          cut -c 1-10 file.txt
2nd column from CSV          cut -d ',' -f 2 data.csv
Multiple fields from         cut -d ':' -f 1,3
passwd                       /etc/passwd
🔹 Syntax
paste [OPTION]... [FILE]...
🔹 How It Works
Each line of the input files is joined together with
a tab (by default), producing one combined line
per output line.
🔹 Examples
1. Basic Horizontal Merge
Given two files:
file1.txt
Alice
Bob
Charlie
file2.txt
Math
Science
English
paste file1.txt file2.txt
Output:
Alice
Math
Bob
Science
Charlie
English
2. Custom Delimiter
paste -d ',' file1.txt file2.txt
→ Uses , instead of a tab.
Output:
Alice,Math
Bob,Science
Charlie,English
Charlie
✅ Summary
Option Description
paste f1 Join files line-by-line with
f2       tabs
-d DELIM Use custom delimiter
          Merge all lines of each file
-s
          into one
🔹 Common Examples
1. Alphabetical Sort
sort file.txt
→ Sorts lines in ascending (A–Z) order.
2. Reverse Sort
sort -r file.txt
→ Sorts lines in descending (Z–A) order.
3. Numeric Sort
sort -n numbers.txt
→ Sorts lines based on numeric value.
🔹 Useful Options
Optio
      Description
n
-r     Reverse order
-n     Numeric sort
-k N   Sort by Nth field/column
-u     Unique lines only
       Set custom delimiter (default is
-t
       space)
-o     Write result to output file
✅ Summary
                       Command
Task
                       Example
Basic sort             sort file.txt
Reverse sort           sort -r file.txt
Numeric sort           sort -n file.txt
Sort by column         sort -k3 file.txt
Remove duplicatessort -u file.txt
Custom delimiter sort -t',' -k2
sort             file.csv
🔹 Basic Syntax
uniq [OPTIONS] [input_file] [output_file]
🔹 Examples
Given file data.txt:
apple
apple
banana
banana
banana
cherry
apple
1. Remove consecutive duplicates:
uniq data.txt
Output:
apple
banana
cherry
apple
✅ Summary
Optio
      Purpose
n
-c       Count occurrences
         Show only duplicate
-d
         lines
         Show only unique
-u
         lines
 Manipulating Characters Using
tr
The tr command in UNIX is used to translate,
delete, or squeeze characters from standard
input and write the result to standard output. It’s
a handy tool for simple character-level
transformations.
🔹 Basic Syntax
tr [OPTION] SET1 [SET2]
     Translates characters in SET1 to
      corresponding characters in SET2.
     Reads from standard input, writes to
      standard output.
🔹 Common Uses of tr
                  Command
Operation                 Description
                  Example
Translate                        Convert all
lowercase to      tr 'a-z' 'A-Z' lowercase letters to
uppercase                        uppercase
Delete            tr -d '0-9'   Delete all digits
                   Command
Operation                  Description
                   Example
characters                      from input
                                Replace multiple
Squeeze
                   tr -s ' '    spaces with single
repeated chars
                                space
                                Replace 'a' with '1',
Replace            tr 'abc'
                                'b' with '2', 'c' with
characters         '123'
                                '3'
                                  Delete all except
Complement
                   tr -cd 'a-z\n' lowercase letters
(invert set)
                                  and newline
🔹 Examples
1. Convert lowercase to uppercase
echo "hello world" | tr 'a-z' 'A-Z'
Output:
HELLO WORLD
4. Replace characters
echo "abcabc" | tr 'abc' '123'
Output:
123123
✅ Summary
Optio
      Meaning
n
-d    Delete characters
-s    Squeeze repeated characters
      Complement set (invert
-c
      selection)
Searching Patterns Using grep
The grep command is a powerful tool used to
search for specific patterns or strings in files
or input text. It prints lines that match the given
pattern.
🔹 Basic Syntax
grep [OPTIONS] PATTERN [FILE...]
     PATTERN can be a simple string or a regular
      expression.
     If FILE is omitted, grep reads from standard
      input.
🔹 Common Examples
1. Search for a simple word in a file
grep "error" logfile.txt
→ Prints lines containing the word error.
2. Case-insensitive search
grep -i "warning" logfile.txt
→ Matches Warning, WARNING, etc.
🔹 What is BRE?
       BRE defines a syntax for matching text
        patterns.
       Used by default in commands like grep.
       Allows matching characters, ranges,
        repetitions, anchors, and grouping.
🔹 Example Patterns
     Find lines containing "cat" or "cot":
grep 'c[ao]t' file.txt
     Find lines starting with "Error":
grep '^Error' file.txt
     Find lines ending with ".txt":
grep '\.txt$' file.txt
     Find lines with 3 to 5 "a"s in a row:
grep 'a\{3,5\}' file.txt
🔹 Notes
     In BRE, some metacharacters like {}, (), +
      need to be escaped with backslash (\).
     For extended regex (ERE), these do not
      require escaping (use grep -E or egrep).
✅ Summary
                      BRE       Example
Task
                      Pattern   Command
Match any
                      .         grep 'a.b' file
character
Zero or more
                      *         grep 'lo*l' file
repeats
Start of line         ^         grep '^Start' file
End of line           $         grep 'end$' file
Character class       [abc]     grep '[aeiou]' file
                                grep 'a\{2,4\}'
Repetition counts \{m,n\}
                                file
egrep
egrep stands for “extended grep” and is used
to search files for patterns using Extended
Regular Expressions (ERE).
🔹 What is egrep?
     It’s like grep -E.
     Supports more powerful regex features
      without needing to escape special
      characters like {}, +, ?, |, () that you must
      escape in Basic Regular Expressions (BRE).
     Useful for complex pattern matching.
🔹 Basic Syntax
egrep [OPTIONS] PATTERN [FILE...]
🔹 Examples
1. Search for lines containing “cat” or
“dog”
egrep 'cat|dog' file.txt
2. Search for words with optional "u" (color
or colour)
egrep 'colou?r' file.txt
🔹 Note
     Modern systems often alias egrep to grep -
      E.
     egrep is deprecated in some systems;
      prefer grep -E.
✅ Summary
                       Command
Task
                       Example
Use alternation (OR) `egrep 'cat
Use optional           egrep 'colou?r'
character              file
                       Command
Task
                       Example
One or more            egrep 'go+gle'
repetitions            file
Grouping and           egrep '(ab){2,3}'
counts                 file
grep -E
grep -E is the command to use Extended
Regular Expressions (ERE) with grep. It
behaves like egrep (which is often an alias for
grep -E).
🔹 Basic Syntax
grep -E [OPTIONS] PATTERN [FILE...]