Unix
Unix
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
alarm() The alarm system call sets the alarm clock of a process
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:
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
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
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:
In Short:
These are simple command-line tools that make
system tasks easy!
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.
6. Naming Best Practices
• Use lowercase letters, underscores, or hyphens for
readability.
o Example: my_file.txt or my-file.txt
• Avoid spaces; if necessary, use quotes or escape
characters.
Parent Child Relationship:
In UNIX (and UNIX-like systems), the parent-child
relationship refers to how processes are organized and
created.
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
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
cp file.txt $HOME/
Copies file.txt to your home directory
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.
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.
$PWD
Executing this command prints the symbolic path stored in
the $PWD environment variable
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
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
Option Description
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
Option Description
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
Key Action
q Quit
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
Option Description
-n Number of copies
-t Job title
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:
Read line by line while read line; do ... done < file
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
Summary of wc Options
Option Meaning
-l Count lines
-w Count words
-m Count 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
1 Files differ
2 Error occurred
Related Commands
Command Purpose
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
Basic Syntax
diff [options] file1 file2
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
Option Description
-y Side-by-side comparison
Side-by-Side Comparison
diff -y file1.txt file2.txt
Output:
apple apple
banana banana
cherry | date
Summary
Task Command
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
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
Option Description
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
Command Description
Command Action
gzip -dc file.gz > file Uncompress but keep .gz file
Basic Syntax
zip [options] archive_name.zip files_or_directories
Examples
Option Description
Basic Syntax
unzip archive.zip
• Extracts all files from archive.zip into the current
directory.
Common Examples
Option Description
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.
File Ownership Components
Each file/directory is associated with:
1. User (Owner) — The person who created the file
2. Group — A set of users with shared access
3. Other — Everyone else on the system
Changing Ownership
Command Purpose
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)
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
0 --- No permissions
Examples:
chmod 755 file # rwx for user, r-x for group & others
chmod 644 file # rw- for user, r-- for group & others
chmod 700 script # rwx only for owner
2 setgid (s)
4 setuid (s)
Examples:
chmod 4555 file # setuid + rwx for user, r-x for
group/others
chmod 2551 file # setgid + rx for user/others, x for group
chmod 1777 directory # sticky bit + full access for all
3. Changing Permissions Using Symbolic Mode
Format:
chmod [who][operator][permissions] filename
Symbols:
Who:
• u: user
• g: group
• o: others
• a: all (user + group + others)
Operators:
• +: add permission
• -: remove permission
• =: set exact permission
Permissions:
• r: read
• w: write
• x: execute
• s: setuid/setgid
• t: sticky bit
Examples:
chmod o-r file # Remove read from others
chmod a+rx file # Add read & execute for all
chmod g=rwx file # Set group to rwx exactly
Notes:
• Use ls -l to verify changes.
• With ACLs (Access Control Lists), changes may affect
ACL masks. Use getfacl filename to verify
permissions if ACLs are used.
View Ownership:
ls -l filename
Example Output:
-rw-r--r-- 1 alice developers 1234 May 15 10:00 report.txt
Syntax:
chgrp [new_group] filename
Example:
chgrp developers project.doc
What is an Inode?
An inode (index node) is a data structure that stores
metadata about a file (not the file content or name).
Each file and directory has an associated inode.
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.
Summary
Term Description
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
Links to Inode
Summary Table
Shared inode No
Soft Link
Feature Hard Link
(Symbolic Link)
Can link to
Usually not allowed Allowed
directories
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
umask Effect on Final File Effect on
Directory
Value Files Permission Directories
Permission
removes removes
write for 644 (rw-r--r- write for 755 (rwxr-xr-
022
group and -) group and x)
others others
removes
removes
write for 664 (rw-rw- 775
002 write for
others r--) (rwxrwxr-x)
others only
only
removes
removes all
all for 600 (rw------ 700 (rwx-----
077 for group
group and -) -)
and others
others
6. Summary
File Directory
Aspect Effect of umask
Default Default
Modification Time
Last time file content was modified
(mtime)
Access Time
Last time file was read or accessed
(atime)
4. Summary
Command Shows
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.
Scripting
Command History
Auto-completion
Syntax Highlighting
Example:
ls *.txt # All files ending in .txt
ls file?.sh # file1.sh, fileA.sh, but not file10.sh
ls [a-c]* # Files starting with a, b, or c
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
3. Shell Options (For Advanced Globbing)
You can enable extended globbing in bash with:
shopt -s extglob
Then use:
ls !(file1.txt) # Match all except file1.txt
ls +([0-9]) # Match one or more digits
Summary
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
Substitution
Method Description
Allowed?
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:
echo \$HOME # Output: $HOME
echo "She said \"hello\"" # Output: She said "hello"
Example:
file="My File.txt"
rm $file # Tries to remove `My` and `File.txt` as two files
(error!)
rm "$file" # Correct: quotes prevent word splitting
Quick Comparison Table
Interprets $, Preserves
Type Use case
*, etc.? spaces?
Most scripting
"..." Partially Yes
needs
Simple
No
Yes No commands, risky
quotes
input
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
Summary Table
stderr 2 Errors
Example: Script Using stdin
#!/bin/bash
echo "Enter your name:"
read name # reads from stdin
echo "Hello, $name"
Summary
Summary
Output to
(default) Normal stdout echo "hi"
terminal
Overwrite file
Redirect to file > echo hi > out.txt
with output
Summary Table
Operator Description Example
# Discard stderr
command 2> /dev/null
Summary
Discards Suppress
Data is lost
/dev/null everything unwanted
(black hole)
written to it output
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.
Multiple Pipes
You can chain many commands:
cat file.txt | tr 'a-z' 'A-Z' | sort | uniq -c | sort -nr
• Converts text to uppercase, sorts, counts unique
lines, and sorts by frequency.
Summary
Symbol Description Example
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.
Append output to a file instead of overwriting
echo "New line" | tee -a logfile.txt
• -a flag appends instead of replacing.
Summary
Option Description Example
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
Exporting Variables
To make variables available to child processes, use
export:
export PATH=$PATH:/my/custom/path
Special Variables
Variable Meaning
Tips
• Use quotes around variable values with spaces:
var="Hello World"
• Use {} for clarity: ${var}
Summary
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
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
Basic Usage
ps
Shows processes running in the current shell session.
PID Process ID
Summary
Command Description
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
Flow Diagram:
Kernel boot
↓
init (PID 1)
↓
getty (terminal login prompt)
↓
login (user authentication)
↓
User’s Shell (command prompt)
Summary:
Step Role
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
Code Description Example Usage/Meaning
Sleeping
S Waiting for input or resource
(interruptible)
Uninterruptible
D Waiting for I/O (disk/network)
sleep
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
Background Jobs
Background jobs let you run commands without waiting
for them to finish, so you can keep using the shell prompt.
1. Using & Operator
• Add & at the end of a command to run it in the
background.
sleep 30 &
• Shell immediately returns prompt.
• The job runs independently.
• You can see jobs with jobs command.
• Bring job to foreground with fg %job_number.
Job runs in
Yes Yes
background
Survives terminal
No (usually killed) Yes
logout
4. Example
# Run script in background
./backup.sh &
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
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
3. List Jobs
jobs
Shows jobs with job numbers and states.
Summary
Command Description
Useful Options
Option Description
Summary
Command Purpose
Example Workflow
$ sleep 100
# Press Ctrl+Z
[1]+ Stopped sleep 100
$ jobs
[1]+ Stopped sleep 100
$ bg %1 # Resume in background
[1]+ sleep 100 &
$ fg %1 # Bring back to foreground
sleep 100
Summary
Command /
Action Effect
Key
Resume in fg
Bring job to foreground
foreground %job_number
Killing a Job
You can kill a job that’s running or stopped in your current
shell session by sending it a termination signal.
1. at Command
• Schedules a command or script to run once at a
specific time.
• The job runs when the system clock reaches the
specified time.
• Requires the at daemon (atd) running on the system.
Basic Usage
at 14:30
Then type commands you want to run at 2:30 PM, end
input with Ctrl+D.
Example:
at 22:00
at> /home/user/backup.sh
at> <Ctrl+D>
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
Command Purpose When It Runs
MODULE-6 Customization
Use of Environment Variables
Environment variables in UNIX are key-value pairs that
define settings and behavior for the shell and system
processes. They are inherited by child processes and used
to configure the working environment.
Summary
Command Purpose
Variable Description
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
Syntax Action
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
Command Description
Basic Syntax
pr [options] filename
Common pr Options
Option Description
Examples
1. Format file for printing:
pr myfile.txt
Adds headers with filename, date, and page numbers.
Summary
The pr command is a simple but powerful tool to:
• Prepare text files for printing
• Control page layout
• Format output into columns
• Add headers, margins, and spacing
Summary
Syntax
cut [OPTION]... [FILE]
Common Options
Option Description
-b Select bytes
-c Select characters
Examples
1. Cut by Byte Position
cut -b 1-5 file.txt
→ Prints first 5 bytes from each line.
Summary
Use Case Command Example
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
Mat
h
Bob
Scie
nce
Charlie
Engli
sh
2. Custom Delimiter
paste -d ',' file1.txt file2.txt
→ Uses , instead of a tab.
Output:
Alice,Math
Bob,Science
Charlie,English
Option Description
Basic Syntax
sort [OPTIONS] filename
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
Option Description
-r Reverse order
-n Numeric sort
Summary
Task Command Example
Basic Syntax
uniq [OPTIONS] [input_file] [output_file]
Common Uses and Options
Command Description
sort file.txt |
Removes all duplicates after sorting
uniq
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
Option Purpose
-c Count occurrences
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
lowercase to tr 'a-z' 'A-Z'
letters to uppercase
uppercase
Replace multiple
Squeeze repeated
tr -s ' ' spaces with single
chars
space
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
Option Meaning
-d Delete characters
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.
Option Description
-i Case-insensitive search
-r Recursive search
-c Count matches
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.
Any single
. a.b aab, acb, a1b
character
Zero or more of
* lo*l ll, lol, lool, loool
preceding char
Any vowel
[...] Character class [aeiou]
character
Negated character
[^...] [^0-9] Any non-digit
class
Repetition (m to n
\{m,n\} a\{2,4\} aa, aaa, or aaaa
times)
Symbol Meaning Example Matches
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
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...]
go+gle matches
One or more
+ gogle, google,
occurrences
gooogle
` ` Alternation (OR)
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
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...]
` `
() Grouping
Why Use grep -E?
• More concise patterns without backslashes.
• Compatible with modern scripting.
• Same powerful matching as egrep.
MODULE-7 INTRODUCTION TO
SHELL SCRIPTS
Simple Shell Scripts
A shell script is a text file containing a sequence of shell
commands. These scripts are executed by the shell (like
bash, sh, etc.) and are used to automate repetitive tasks.
case $choice in
1) date ;;
2) pwd ;;
3) who ;;
*) echo "Invalid option" ;;
esac
Tip Description
Features Used
Feature Description
Output:
First argument: Hello
Second argument: World
All arguments: Hello World
Total number of arguments: 2
Variable Meaning
$# Number of arguments
$0 Script name
if [ $# -ne 2 ]; then
echo "Usage: $0 num1 num2"
exit 1
fi
sum=$(( $1 + $2 ))
echo "Sum: $sum"
Run:
./add.sh 10 20
Output:
Sum: 30
Explanation:
• cd newdir will only execute if mkdir newdir is
successful.
2. || – OR Operator
• Runs the second command only if the first
command fails (exit status ≠ 0).
• Equivalent to "try this, or if it fails, try that".
Example:
cd myfolder || echo "Folder does not exist"
Explanation:
• If cd myfolder fails, then it will print "Folder does not
exist".
3. Combined Use
mkdir testdir && cd testdir || echo "Failed to create and
enter directory"
• If mkdir succeeds and cd fails, it shows error
message.
• Combines both conditions.
4. In if Statements
if [ -f myfile ] && [ -r myfile ]; then
echo "File exists and is readable"
fi
• Checks both conditions before executing the block.
Summary Table
` `
1. if Statement
Used to execute commands based on conditions.
Syntax:
if [ condition ]; then
commands
elif [ another_condition ]; then
other_commands
else
default_commands
fi
Use [ ... ] or [[ ... ]] for conditions.
2. case Statement
Used to match a value against multiple patterns. Good
for menu-style options.
Syntax:
case $variable in
pattern1)
commands ;;
pattern2)
commands ;;
*)
default_commands ;;
esac
case $choice in
1) date ;;
2) ls ;;
3) who ;;
*) echo "Invalid option" ;;
esac
Summary
Statement Use for Example
2. Types of Expressions
File Conditions
Expression Meaning
Example:
if [ -f myfile ]; then
echo "File exists"
fi
String Conditions
Expression Meaning
Example:
if [ "$name" = "admin" ]; then
echo "Welcome, admin"
fi
Integer Comparisons
Expression Meaning
a -eq b Equal
Example:
if [ $x -gt 10 ]; then
echo "x is greater than 10"
fi
Example:
if [[ $name == a* ]]; then
echo "Name starts with 'a'"
fi
Summary
Tool Purpose
Addition
expr 5 + 3
# Output: 8
Subtraction
expr 10 - 4
# Output: 6
Multiplication (escape *)
expr 6 \* 2
# Output: 12
Division
expr 8 / 2
# Output: 4
Modulus (remainder)
expr 9 % 4
# Output: 1
sum=$(expr $a + $b)
echo "Sum is: $sum"
Use $(...) or backticks `expr ...` to assign the result to
a variable.
Length of a string:
expr length "hello"
# Output: 5
Substring:
expr substr "universe" 2 3
# Output: "niv"
4. Comparison Operators
expr 5 = 5 # Returns 1 (true)
expr 5 != 3 # Returns 1
expr 5 \> 3 # Returns 1 (use \> to escape '>')
expr 2 \< 1 # Returns 0 (false)
Tips
• Always use spaces between operands and operators.
• Escape special characters (*, <, >) with \.
• expr works only with integers, not floating point
numbers.
1. String Length
expr length "hello"
# Output: 5
Or using a variable:
str="unixshell"
expr length "$str"
2. Substring Extraction
expr substr "universe" 2 3
# Output: "niv"
Syntax:
expr substr STRING POSITION LENGTH
4. String Comparison
expr "apple" = "apple"
# Output: 1 (true)
Summary
1. for Loop
2. while Loop
Runs as long as a condition is true.
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
count=$((count + 1))
done
Summary
Loop Type Use Case
$0 Script name
$# Number of arguments
Tips
• Always quote parameters like "$1" to avoid issues
with spaces.
• Use $# to validate input count.
• Use shift to move parameters (helpful in parsing
multiple inputs).
SYSTEM ADMINISTRATION
A UNIX System Administrator plays a critical role in
managing and maintaining UNIX-based systems. Their
responsibilities ensure that the systems are running
efficiently, securely, and reliably. Here are the essential
duties of a UNIX system administrator:
5. Security Management
• Apply patches and updates to the OS and software.
• Configure firewalls and access control lists (ACLs).
• Monitor for security breaches and maintain system
integrity.
• Implement security tools (e.g., SELinux, auditd).
System Shutdown
1. Notify Users (Optional but Recommended)
• Use wall to broadcast shutdown notices to logged-in
users.
• wall "System going down for maintenance in 10
minutes"
2. Commands to Shut Down Safely
• Common commands:
• shutdown -h now # Halt immediately
• shutdown -r +5 "Rebooting in 5 minutes" # Reboot
with delay
• init 0 # Shutdown
• init 6 # Reboot
• poweroff # Power off
• reboot # Reboot
• halt # Halt system
3. Graceful Termination
• All users are logged off.
• System processes and services are stopped.
• Filesystems are unmounted cleanly.
• Logs are written and sync'd.
1. Username
• A unique identifier for each user.
• Created using:
• useradd <username>
• Stored in /etc/passwd.
2. Password
• Secures user access to the system.
• Set or changed using:
• passwd <username>
• Encrypted password stored in /etc/shadow.
3. Home Directory
• Default location where a user is placed after login.
• Stores personal files and settings (e.g., .bashrc,
.profile).
• Typically located at /home/<username>.
• Set during user creation:
• useradd -d /home/username username
4. Group ID (GID)
• Users belong to one primary group and can be added
to supplementary groups.
• Group information is stored in /etc/group.
• Set during user creation:
• useradd -g <primary_group> -G <other_groups>
<username>
5. Disk Quota
• Limits the amount of disk space a user can consume.
• Useful for multi-user systems to prevent abuse.
• Enable quotas on the filesystem, then assign limits:
• edquota <username>
• quota -u <username> # View usage
6. Terminal (Shell)
• Defines the command-line interface the user gets.
• Common shells: /bin/bash, /bin/sh, /bin/ksh,
/bin/zsh.
• Set during user creation:
• useradd -s /bin/bash <username>
• Can be changed later with chsh.
Important Files Involved
File Purpose