🇮🇳INDEPENDENCE DAY OFFER25% OFF LIVE
ENDS 16 AUG 8:00 PM IST:6h 30m 46s LEFT
Plans from ₹374 (Reg. ₹499)
📢 Have suggestions, questions, or interview doubts? Share your queries — answers will be updated module-wise. Contact: vlsiphysicaldesignocean@gmail.com

Module 4

Linux & Basic Tcl Script

Select Reading View:

Linux - Topics Covered

TCL - Topics Covered

Introduction to Linux Operating System


1. What is an Operating System (OS)?

An Operating System is a system software that acts as an interface between the user and the computer hardware.

Main functions of an Operating System

  • Controls and manages hardware (CPU, memory, disk, I/O devices)
  • Allows users to run applications
  • Manages files and folders
  • Provides security and access control

Without Operating System

  • Computer cannot work
  • User cannot interact with hardware directly

Examples of Operating Systems

  • Windows
  • Linux
  • macOS
  • Android
  • iOS

Graphic showing Open Source collaborative development model

2. What is Linux?

Linux is a free and open-source operating system based on UNIX principles.

Key points about Linux

  • Developed by Linus Torvalds (1991)
  • Open source (source code is freely available)
  • Highly secure and stable
  • Used in servers, mobiles, supercomputers, cloud, and embedded systems

Where Linux is used

  • Servers (Google, Amazon, Facebook)
  • Mobile phones (Android)
  • Cloud platforms
  • Cybersecurity tools
  • Programming and development

Application layer in the Linux ecosystem

3. Why Do We Need an Operating System?

Operating systems are required because:
  • Hardware understands only binary (0s and 1s)
  • Users understand commands and applications
  • OS converts user instructions into hardware operations

Roles of OS

User

OS

Hardware

Gives command

Translates

Executes


Conceptual diagram of Linux security and stability architecture

4. Components of Linux Operating System

Linux operating system consists of three main components:
  1. Kernel
  2. Shell
  3. Utilities / Applications

User interaction with the Linux Shell interface

5. What is Kernel?

The Kernel is the core (heart) of the operating system.

Definition

Kernel is the central program that directly interacts with hardware and manages system resources.

Functions of Kernel

  • Process management (CPU scheduling)
  • Memory management
  • Device management
  • File system management
  • System call handling

Important Point

User cannot directly access hardware  Kernel controls all hardware access

Diagram of multi-user and multi-tasking capabilities in Linux

6. Why Kernel is Important?

Without kernel:
  • No memory management
  • No multitasking
  • No device communication
  • System will crash

Types of Kernels

  • Monolithic Kernel (Linux)
  • Microkernel
  • Hybrid Kernel

Illustration of Linux operating system versatility across devices

7. What is Shell?

The Shell is a command interpreter that acts as an interface between user and kernel.

Definition

Shell is a program that takes user commands, interprets them, and sends them to the kernel for execution.

Shell works like a translator

  • User → Shell → Kernel → Hardware

Community support network illustration for Linux

8. Types of Shells in Linux

Shell Name

Description

Bash

Most common shell

Sh

Bourne Shell

Zsh

Advanced shell

Fish

User-friendly shell


Free and open source software logo

9. Why Do We Use Shell in Linux?

Shell is used because:
  • Faster than GUI
  • Powerful scripting support
  • Automates tasks
  • Required for server administration

Example

Command to list files: ls

Motivation graphic for learning Linux systems

10. Difference Between Kernel and Shell

Kernel

Shell

Core of OS

Interface to OS

Manages hardware

Takes user commands

Runs in background

User interacts with it

Cannot be replaced easily

Can be changed


Career growth pathways in Linux and DevOps

11. Why Linux is Preferred?

  • Free and open source
  • Secure and stable
  • High performance
  • Multiuser & multitasking
  • Used in real-world industry

Graphic indicating system uptime without reboots

12. Summary (For Students)

  • OS connects user and hardware
  • Linux is a free, open-source OS
  • Kernel is the heart of Linux
  • Shell is the command interface
  • Linux is powerful, secure, and widely used

One-Line Revision

“Linux = Kernel + Shell + Utilities”

Linux File System & Paths (With Commands Explained Clearly)


1. What is a Path in Linux?

A path is the location (address) of a file or folder inside the Linux system. Just like:
  • House address → helps you reach a house
  • Linux path → helps Linux reach a file

Industry usage statistics for Linux servers

2. Root Directory (/) – The Starting Point

What is Root Directory?

  • Root directory is the top-most folder in Linux
  • Represented by /
  • All files and folders start from here
Important Linux has only one root directory

Real Example

/ Everything like /home, /bin, /etc comes under this.

Icon representing the lightweight nature of Linux kernel

3. Absolute Path (Full Address)

What is Absolute Path?

  • Path that starts from root directory (/)
  • Gives complete location
  • Works from anywhere

Real Example

/home/student/Documents/notes.txt This means:
  • Start from /
  • Go to home
  • Then student
  • Then Documents
  • Open notes.txt

Command Used – cd (Change Directory)

What cd does

  • Moves you from one folder to another

Real Example

cd /home/student/Documents No matter where you are, Linux takes you to Documents

The Kernel layer in Linux architecture

4. Relative Path (Nearby Address)

What is Relative Path?

  • Path based on current location
  • Does not start with /
  • Shorter and faster to type

Real Example

Current directory: /home/student Relative path: Documents/notes.txt

Command Example

cd Documents Linux understands: “Go inside Documents which is inside my current folder”

System utilities and tools in Linux

5. pwd Command (Where Am I?)

What is pwd?

  • pwd means Print Working Directory
  • Shows current location

Why we use it

  • To avoid confusion
  • To know exactly where we are

Example

pwd Output: /home/student/Linux Means you are inside Linux folder

The Root directory (/) in Linux file hierarchy

6. ls Command (What is Inside?)

What is ls?

  • Lists files and folders in a directory

Real-Life Example

Like opening a bag to see what is inside

Examples

ls Shows files in current folder ls /home/student Shows files inside student folder

/bin directory containing essential binary executables

7. cd Command (Move Between Folders)

What is cd?

  • Changes directory
  • Helps move inside folders

Examples

Go to home directory: cd /home/student Go back one step: cd .. Go to home directly: cd ~

/sbin directory for system administrator binaries

8. mkdir Command (Create Folder)

What is mkdir?

  • Creates a new directory

Real Example

mkdir LinuxNotes A folder named LinuxNotes is created

9. rmdir Command (Delete Empty Folder)

What is rmdir?

  • Deletes empty directories only

Example

rmdir LinuxNotes

/etc directory for system configuration files

10. Special Path Symbols (Very Important)

Symbol

Meaning

Example

/

Root directory

/home

.

Current directory

./file.txt

..

Parent directory

cd ..

~

Home directory

cd ~


/home directory structure for user files

11. Home Directory (~)

What is Home Directory?

  • Personal space for each user
  • Stores documents, downloads, files

Example

/home/student Shortcut: ~

/root home directory for the superuser

12. Practical Real Example (Lab Style)

Step 1: Check location

pwd

Step 2: Create folder

mkdir LinuxClass

Step 3: Enter folder

cd LinuxClass

Step 4: Verify

pwd Output: /home/student/LinuxClass

/var directory for variable data like logs and spool files

13. Student Revision Summary

  • pwd → Where am I?
  • ls → What is inside?
  • cd → Move folders
  • mkdir → Create folder
  • Absolute path → Full address
  • Relative path → Nearby address

Final One-Line Understanding

Linux paths are addresses, and commands help us move, see, and manage those a LINUX FILE & DIRECTORY COMMANDS – DETAILED LECTURE NOTES

1. pwd – Present Working Directory

What is pwd?

pwd shows where you are currently working in the Linux file system. Linux is hierarchical (tree structure). If you don’t know your location, you may work on the wrong files.

Example 1

pwd Output: /home/student Means: You are inside the student directory.

Example 2

cd Documents pwd First you move into Documents  Then pwd confirms your new location

Example 3

cd / pwd Shows root directory /

2. ls – List Directory Contents

What is ls?

Used to see files and directories inside a folder.

Example 1 (Basic)

ls Shows only names of files & folders

Example 2 (Detailed view)

ls -l Shows:
  • Permissions
  • Owner
  • Size
  • Date

Example 3 (Hidden files)

ls -a Shows hidden files like .bashrc

Example 4 (Human readable size)

ls -lh File size shown in KB, MB instead of bytes

3. cd – Change Directory

What is cd?

Used to move between directories.

Example 1

cd Downloads Moves into Downloads folder

Example 2

cd .. Moves one level up (parent directory)

Example 3

cd ~ Moves directly to home directory

4. mkdir – Make Directory

What is mkdir?

Used to create new directories.

Example 1

mkdir Linux Creates a folder named Linux

Example 2

mkdir Class1 Class2 Creates multiple directories at once

Example 3 (Nested directories)

mkdir -p Linux/Notes/Day1 Creates parent & child directories together

5. rmdir – Remove Empty Directory

What is rmdir?

Deletes empty directories only.

Example 1

rmdir Test Deletes Test if empty

Example 2

rmdir Dir1 Dir2 Deletes multiple empty directories

Example 3 (Fails if not empty)

rmdir Linux Error if Linux contains files

6. touch – Create File / Update Time

What is touch?

Creates empty files or updates timestamp.

Example 1

touch file.txt Creates an empty text file

Example 2

touch a.txt b.txt c.txt Creates multiple files

Example 3

touch oldfile.txt Updates modification time if file exists

7. cat – View File Content

What is cat?

Displays entire content of a file.

Example 1

cat file.txt Shows full file content

Example 2

cat file1.txt file2.txt Displays both files together

Example 3

cat > new.txt Hello Linux Ctrl+D Creates file and writes content

8. less – View Large Files

What is less?

Used to read big files page by page.

Example 1

less logfile.txt Scroll using arrow keys

Example 2

less /etc/passwd Safely read system files

Example 3

ps aux | less View output page by page

9. head – First Lines of File

What is head?

Shows top lines of a file.

Example 1

head file.txt Shows first 10 lines

Example 2

head -5 file.txt Shows first 5 lines

Example 3

head /etc/passwd Quickly view important file header

10. tail – Last Lines of File

What is tail?

Shows last lines, mainly for logs.

Example 1

tail file.txt Shows last 10 lines

Example 2

tail -5 file.txt Shows last 5 lines

Example 3 (Live monitoring)

tail -f logfile.txt Watches logs live

11. cp – Copy Files & Directories

What is cp?

Copies files or directories.

Example 1

cp a.txt b.txt Copies a.txt to b.txt

Example 2

cp a.txt /home/student/ Copies file to another directory

Example 3 (Directory copy)

cp -r Dir1 Dir2 Copies entire directory

12. mv – Move / Rename

What is mv?

Used to move OR rename.

Example 1 (Rename)

mv old.txt new.txt

Example 2 (Move)

mv file.txt Documents/

Example 3

mv *.txt Backup/ Moves all txt files

13. rm – Remove Files & Directories

⚠ Dangerous command

Example 1

rm file.txt

Example 2

rm -r Folder/ Deletes folder and content

Example 3

rm -f file.txt Force delete without confirmation

14. find – Search Files

What is find?

Search files based on name, type, size.

Example 1

find . -name file.txt

Example 2

find /home -type d Finds directories

Example 3

find . -name "*.txt" Finds all text files

15. grep – Search Inside Files

What is grep?

Search text inside files.

Example 1

grep linux notes.txt

Example 2

grep -i linux notes.txt Case-insensitive search

Example 3

ls | grep txt Filters output

16. which – Command Location

What is which?

Shows where command is installed.

Example 1

which ls

Example 2

which bash

Example 3

which python

17. echo – Display Output

What is echo?

Prints text or variables.

Example 1

echo Hello Linux

Example 2

echo $SHELL

Example 3

echo "Today is Linux class"

FINAL STUDENT UNDERSTANDING FLOW

1️⃣ Where am I? → pwd 2️⃣ What is here? → ls 3️⃣ Go somewhere → cd 4️⃣ Create → mkdir, touch 5️⃣ View → cat, less, head, tail 6️⃣ Copy/Move → cp, mv 7️⃣ Delete → rm 8️⃣ Search → find, grep 9️⃣ Know command → which

LINUX EDITORS – DETAILED LECTURE NOTES


1. What is an Editor?

Definition:

An editor is a software tool used to create, modify, and save text files. In Linux:
  • Configuration files
  • Program code
  • Scripts
  • Logs
    are
    text-based, so editors are very important.

Why Editors are Important in Linux?

  • Linux is command-line driven
  • Almost everything is configured using text files
  • Editors allow:
  • Editing system files
  • Writing shell scripts
  • Programming

2. Types of Editors in Linux

Linux editors are mainly divided into two categories:

A. CLI Editors (Command Line Editors)

  • Work inside terminal
  • Lightweight
  • Very powerful
Examples:
  • vi
  • vim
  • rvim
  • nano

B. GUI Editors (Graphical Editors)

  • Mouse-based
  • Window interface
Examples:
  • gvim
  • gedit
  • kate

3. Vi Editor

What is vi?

  • Oldest and most basic Linux editor
  • Available in almost all Linux systems
  • Modal editor (works in modes)

Characteristics:

  • Lightweight
  • Keyboard-based
  • Difficult for beginners
  • Foundation for vim & gvim

4. Vim Editor

What is vim?

vim = Vi Improved

Advantages over vi:

  • Syntax highlighting
  • Undo/Redo
  • Plugins support
  • Better search

Command:

vim file.txt

5. rvim Editor

What is rvim?

rvim = Restricted Vim

Purpose:

  • Used for security
  • Restricts:
  • Shell commands
  • File system access

Usage:

rvim file.txt

6. GVIM Editor (MAIN FOCUS)

What is GVIM?

gvim = Graphical Vim

Features:

  • GUI-based vim
  • Mouse support
  • Menus & toolbar
  • Same power as vim + graphical interface

Why GVIM is Best for Learning?

Easy for beginners  Visual support  Same commands as vim  Used in real-world development

Command to Open GVIM:

gvim file.txt

7. GVIM MODES (VERY IMPORTANT)

GVIM works using MODES.

Total Main Modes:

1️⃣ Normal Mode 2️⃣ Insert Mode 3️⃣ Visual Mode 4️⃣ Command-Line Mode 5️⃣ Replace Mode

8. Normal Mode (Default Mode)

What is Normal Mode?

  • Default mode when GVIM opens
  • Used for:
  • Navigation
  • Copy, delete
  • Editing commands
🚫 Cannot type text directly

Important Normal Mode Commands (Systematic Order)

A. Cursor Movement

Command

Action

h

Move left

l

Move right

j

Move down

k

Move up


B. Word Movement

Command

Action

w

Next word

b

Previous word

e

End of word


C. Line Movement

Command

Action

0

Start of line

$

End of line

gg

First line

G

Last line


D. Delete Commands

Command

Action

x

Delete character

dd

Delete line

dw

Delete word

d$

Delete till end


Example

Linux is powerful
  • Cursor on "is"
  • Press dw → deletes "is"

9. Insert Mode

What is Insert Mode?

  • Used to type text
  • Similar to Notepad typing

Enter Insert Mode

Command

Action

i

Insert before cursor

I

Insert at line start

a

Insert after cursor

A

Insert at line end

o

New line below

O

New line above


Exit Insert Mode

ESC

Example:

  1. Press i
  2. Type: Linux Editor
  3. Press ESC

10. Visual Mode

What is Visual Mode?

  • Used to select text
  • Similar to mouse selection

Enter Visual Mode

Command

Action

v

Character selection

V

Line selection

Ctrl + v

Block selection


Visual Mode Operations

Command

Action

y

Copy

d

Delete

>

Indent right

<

Indent left


Example:

  1. Press V
  2. Select lines
  3. Press y → copied

11. Command-Line Mode

What is Command Mode?

  • Used to:
  • Save file
  • Quit
  • Search
  • Replace

Enter Command Mode

:

File Commands

Command

Meaning

:w

Save

:q

Quit

:wq

Save & Quit

:q!

Force quit

:w!

Force save


Search Commands

Command

Meaning

/word

Search forward

?word

Search backward

n

Next match

N

Previous match


Replace Command

:%s/old/new/g Replace all occurrences

Example:

:%s/linux/Linux/g

12. Replace Mode

What is Replace Mode?

  • Replaces text instead of inserting

Enter Replace Mode

R

Example:

  • Press R
  • Type new text
  • Existing text is overwritten

13. GVIM WORKFLOW (REAL LIFE)

1️⃣ Open file → gvim file.txt 2️⃣ Navigate → Normal Mode 3️⃣ Edit → Insert Mode 4️⃣ Select → Visual Mode 5️⃣ Save → Command Mode

14. Why GVIM is Used in Industry?

Configuration editing  Programming  Remote system editing  Fast editing

15. STUDENT SUMMARY (ONE GLANCE)

Mode

Purpose

Normal

Navigation & commands

Insert

Typing text

Visual

Select text

Command

Save, search

Replace

Overwrite

GVIM EDITOR – COMPLETE COMMANDS (DETAILED LECTURE NOTES)


1. GVIM MODES (REVISION)

GVIM works using modes. Commands depend on which mode you are in.

Mode

Purpose

Normal Mode

Navigation, delete, copy

Insert Mode

Typing text

Visual Mode

Selection

Command Mode

Save, search, replace

Replace Mode

Overwrite text


2. NORMAL MODE COMMANDS (MOST IMPORTANT)

Default mode when GVIM opens

2.1 Cursor Movement Commands

Command

Meaning

h

Move left

l

Move right

j

Move down

k

Move up

Examples:

Linux World
  • Press j → moves to World
  • Press k → back to Linux

2.2 Word Navigation Commands

Command

Meaning

w

Next word

b

Previous word

e

End of word

Example:

Linux is powerful OS
  • Cursor on Linux
  • w → moves to is
  • e → moves to x

2.3 Line Navigation Commands

Command

Meaning

0

Start of line

^

First non-space character

$

End of line

Example:

Linux System
  • 0 → start (spaces)
  • ^L
  • $ → end

2.4 File Navigation Commands

Command

Meaning

gg

First line

G

Last line

10G

Go to line 10

Ctrl + g

Show line number


3. INSERT MODE COMMANDS

Enter Insert Mode

Command

Action

i

Insert before cursor

a

Insert after cursor

I

Insert at start

A

Insert at end

o

New line below

O

New line above


Examples:

Linux
  • Cursor on L
  • a → type OS
    Result:
Linux OS

4. DELETE COMMANDS (NORMAL MODE)

Command

Meaning

x

Delete character

dw

Delete word

dd

Delete line

D

Delete till end

dG

Delete till end of file


Examples:

Linux is powerful
  • Cursor on is
  • dw → deletes is

Line1 Line2 Line3
  • Cursor on Line2
  • dd → deletes Line2

5. COPY (YANK) COMMANDS

Command

Meaning

yy

Copy line

yw

Copy word

y$

Copy till end

yG

Copy till end file


Example:

Linux is powerful
  • Cursor on Linux
  • yw
  • Move cursor → p
  • Word pasted

6. PASTE COMMANDS

Command

Meaning

p

Paste after cursor

P

Paste before cursor


7. UNDO / REDO

Command

Meaning

u

Undo

Ctrl + r

Redo


Example:

  • Delete a line
  • Press u → restored

8. VISUAL MODE COMMANDS

Enter Visual Mode

Command

Mode

v

Character

V

Line

Ctrl + v

Block


Visual Mode Operations

Command

Meaning

y

Copy

d

Delete

>

Indent

<

Outdent


Example:

  • Press V
  • Select 3 lines
  • > → indented

9. SEARCH COMMANDS

Command

Meaning

/word

Search forward

?word

Search backward

n

Next

N

Previous


Example:

Linux is Linux
  • /Linux
  • n → next Linux

10. COMMAND MODE COMMANDS

Enter Command Mode

:

File Commands

Command

Action

:w

Save

:q

Quit

:wq

Save & quit

:q!

Force quit

:w!

Force save


Example:

:w myfile.txt (Save as new file)

11. REPLACE COMMANDS

Single Replace

Command

Meaning

r

Replace one character


Global Replace

:%s/old/new/g

Examples:

:%s/linux/Linux/g Replace everywhere :5,10s/a/A/g Replace only lines 5–10

12. MULTI-FILE COMMANDS

Command

Meaning

:e file

Open file

:n

Next file

:prev

Previous

:ls

List files

:bd

Close file


13. WINDOW / SPLIT COMMANDS

Command

Meaning

:split

Horizontal split

:vsplit

Vertical split

Ctrl+w w

Switch window

Ctrl+w q

Close split


14. SETTINGS COMMANDS

Command

Meaning

:set nu

Show line numbers

:set nonu

Hide numbers

:set ic

Ignore case

:syntax on

Syntax highlight


15. HELP COMMAND

Command

Meaning

:help

Open help

:help dd

Help on dd


16. REAL-TIME GVIM USAGE EXAMPLE

Editing Config File:

gvim /etc/passwd
  • /root
  • dd
  • :wq

17. COMPLETE STUDENT SUMMARY

Navigation  Editing  Copy/Paste  Search  Replace  Multi-file  Splits  Settings

LINUX WILDCARD CHARACTERS (PATTERN MATCHING)

(Complete Beginner-to-Advanced Notes)


1. What is a Wildcard Character?

A wildcard is a special character used in Linux shell to represent one or more characters in file or directory names. Instead of typing full file names, we use patterns.

Example:

file1.txt file2.txt file3.txt Instead of: rm file1.txt file2.txt file3.txt We can use: rm file*.txt

2. Why Do We Use Wildcards?

Save time  Handle multiple files  Powerful file filtering  Used in ls, cp, mv, rm, find, grep

3. Types of Wildcard Characters

Linux mainly supports these wildcard characters:

Wildcard

Name

*

Asterisk

?

Question mark

[ ]

Bracket expression

{ }

Brace expansion

!

Negation (inside brackets)


4. Asterisk Wildcard (*)

4.1 Meaning

* matches ZERO or MORE characters

4.2 Examples

Example 1: List all files

ls * Lists all files and directories

Example 2: Files starting with name

ls file* Matches: file.txt file1.txt file_backup.txt

Example 3: Files ending with extension

ls *.txt Matches: notes.txt data.txt

Example 4: Copy multiple files

cp *.txt /backup/ Copies all .txt files

Example 5: Remove files

rm log* Deletes: log1 log2.txt log_backup ⚠ Be careful with rm *

5. Question Mark (?) Wildcard

5.1 Meaning

? matches EXACTLY ONE character

5.2 Examples

Example 1:

ls file?.txt Matches: file1.txt file2.txt Does NOT match: file10.txt

Example 2:

ls ???.txt Matches: abc.txt one.txt

Example 3:

rm data?.csv Deletes: data1.csv data2.csv

Difference Between * and ?

*

?

Zero or more chars

Exactly one char

file* → file, file1

file? → file1


6. Bracket Wildcard [ ]

6.1 Meaning

[ ] matches ANY ONE character from the list or range

6.2 Examples

Example 1: Specific characters

ls file[123].txt Matches: file1.txt file2.txt file3.txt

Example 2: Character range

ls file[a-z].txt Matches: filea.txt fileb.txt

Example 3: Numbers range

ls report[0-9].pdf Matches: report1.pdf report9.pdf

6.3 Bracket with Negation [! ]

Meaning:

Matches NOT these characters

Example:

ls file[!1].txt Matches: file2.txt file3.txt Excludes: file1.txt

7. Brace Expansion { }

7.1 Meaning

{ } is used to generate multiple strings

7.2 Examples

Example 1:

ls file{1,2,3}.txt Expands to: file1.txt file2.txt file3.txt

Example 2:

touch day{1..5}.txt Creates: day1.txt day2.txt day3.txt day4.txt day5.txt

Example 3:

cp file.{txt,pdf} /backup/ Copies: file.txt file.pdf

8. Combining Wildcards (Advanced Usage)

Example 1:

ls *[0-9]?.log Matches: error12.log data9a.log

Example 2:

rm report[!0-9]*.txt Deletes all reports not starting with numbers

9. Real-Time Use Cases

Find log files:

ls /var/log/*.log

Backup files:

cp *.conf /backup/

Delete temp files:

rm *.tmp

10. Important Notes for Students

⚠ Wildcards are processed by shell, not command ⚠ Use ls before rm to verify ⚠ Wildcards do NOT match hidden files (.file) To match hidden files: ls .*

11. Student Quick Summary Table

Wildcard

Use

*

Any length

?

One character

[ ]

One from set

[! ]

Not from set

{ }

Multiple names

LINUX FILE & DIRECTORY PERMISSIONS

(Complete Beginner → Practical Level Notes)


1. Why Permissions Are Needed in Linux

Linux is a multi-user operating system. Many users can access the same system at the same time. Permissions ensure:
  • Data security
  • Controlled access
  • Protection from accidental deletion
  • Proper system management

2. Types of Users in Linux

Every file and directory has 3 permission categories:

Category

Meaning

User (u)

Owner of the file

Group (g)

Group of users

Others (o)

Everyone else


3. Understanding ls -l Output

Command: ls -l Example output: -rwxr-xr-- 1 khalil dev 1234 notes.txt Breakdown:

Field

Meaning

-

File type

rwx

User permissions

r-x

Group permissions

r--

Others permissions

khalil

Owner

dev

Group


4. File Types

Symbol

Meaning

-

Regular file

d

Directory

l

Link


5. Permission Types

Permission

Symbol

File Meaning

Directory Meaning

Read

r

View file content

List files

Write

w

Modify file

Create/Delete files

Execute

x

Run file

Enter directory


6. Permission Structure (9 Bits)

rwx r-x r-- u   g   o
  • First 3 → User
  • Next 3 → Group
  • Last 3 → Others

7. Permissions on Files vs Directories

File

Permission

Effect

r

Can read file

w

Can modify

x

Can execute


Directory

Permission

Effect

r

Can list files

w

Can create/delete

x

Can enter (cd)


8. Symbolic Mode of chmod

Syntax:

chmod [u/g/o/a][+/-/=][r/w/x] filename

9. Symbol Meaning

Symbol

Meaning

+

Add permission

-

Remove permission

=

Assign exact permission


10. Examples – Symbolic Mode

Add execute permission to user:

chmod u+x script.sh

Remove write permission from group:

chmod g-w notes.txt

Give read-only to others:

chmod o=r report.txt

Give full permission to user:

chmod u=rwx file.txt

Give permissions to all:

chmod a+rx data.txt

11. Octal (Numeric) Permission System

Numeric Values:

Permission

Value

r

4

w

2

x

1


Permission Calculation

Permission

Value

rwx

7

rw-

6

r--

4

r-x

5

---

0


12. Common Octal Examples

755

rwx r-x r-x Command: chmod 755 file.sh

644

rw- r-- r-- Command: chmod 644 notes.txt

777 (Dangerous )

rwx rwx rwx Command: chmod 777 test.txt

13. Directory Permission Examples

Allow everyone to enter directory:

chmod 755 mydir

Private directory:

chmod 700 private

14. Recursive Permission Change

chmod -R 755 project/ Changes permission for:
  • Folder
  • All subfolders
  • All files

15. chown – Change Owner

Syntax:

chown user filename

Example:

chown ravi file.txt

Change owner & group:

chown ravi:dev report.txt

Recursive ownership:

chown -R ravi:dev project/ ⚠ Only root can use chown

16. chgrp – Change Group

Syntax:

chgrp group filename

Example:

chgrp admin notes.txt

Recursive:

chgrp -R admin project/

17. Real-World Scenario Example

Create secure project folder:

mkdir project chown khalil:dev project chmod 750 project Result:
  • Owner → Full access
  • Group → Read + Execute
  • Others → No access

18. Common Mistakes Students Make

Using 777 always  Forgetting execute permission on directories  Removing read permission but expecting ls to work

19. Quick Revision Table

Command

Purpose

chmod

Change permissions

chown

Change owner

chgrp

Change group

ls -l

View permissions


Advertisement

20. Student Final Summary

  • Linux permissions protect files
  • Three levels: User, Group, Others
  • Two methods: Symbolic & Octal
  • Directories behave differently
  • chown & chgrp control ownership

LINUX REDIRECTION OPERATORS

(Input & Output Redirection – Complete Beginner Guide)


1. What is Redirection in Linux?

By default in Linux:
  • Input → Keyboard
  • Output → Screen (Terminal)
Redirection allows us to change the direction of input or output to:
  • Files
  • Other commands

2. Standard Streams in Linux

Every command uses 3 standard streams:

Stream

Name

Number

Default

Standard Input

stdin

0

Keyboard

Standard Output

stdout

1

Screen

Standard Error

stderr

2

Screen


3. Types of Redirection

1️⃣ Output Redirection 2️⃣ Input Redirection 3️⃣ Here Document (<<)

4. Output Redirection Operator >

Meaning:

Redirect output of a command to a file ⚠ Overwrites existing file

Syntax:

command > filename

Example 1:

ls > files.txt Output of ls goes into files.txt

Example 2:

date > today.txt Date stored in file

Example 3:

echo "Linux is powerful" > note.txt Text saved into file

Important Point:

If file exists → Content erased & replaced

5. Append Output Redirection >>

Meaning:

Redirect output and append to file  Existing data is not removed

Syntax:

command >> filename

Example 1:

date >> log.txt Adds date at end of file

Example 2:

echo "Second line" >> note.txt

Example 3:

ls >> files.txt Adds directory list again

Difference: > vs >>

Operator

Behavior

>

Overwrite

>>

Append


6. Input Redirection Operator <

Meaning:

Take input from a file instead of keyboard

Syntax:

command < filename

Example 1:

cat < file.txt Displays content of file

Example 2:

wc -l < file.txt Counts lines in file

Example 3:

sort < names.txt Sorts file content

Without <, you would type input manually

7. Here Document Operator <<

Meaning:

Provide multiple lines of input directly in terminal

Syntax:

command << DELIMITER text text DELIMITER

Example 1:

cat << EOF Hello This is Linux EOF Output shown on screen

Example 2:

wc -w << END Linux is an operating system END Word count printed

Example 3:

cat << DATA > file.txt Line one Line two DATA Data written into file

EOF, END, DATA → Any word (must match exactly)

8. Real-World Use Case

Create file without editor:

cat << EOF > info.txt Name: Ravi Course: Linux EOF

9. Error Redirection (Bonus – Important)

Redirect errors only:

command 2> error.txt

Example:

ls wrongfile 2> error.log

Redirect both output & error:

command > all.txt 2>&1

10. Combined Redirection

Example:

sort < input.txt > output.txt Reads from file  Writes sorted output to new file

11. Redirection Summary Table

Operator

Purpose

>

Output overwrite

>>

Output append

<

Input from file

<<

Multi-line input

2>

Error output


12. Common Student Mistakes

Using > instead of >>  Forgetting delimiter in <<  Overwriting important files

13. Simple Student Practice Tasks

1️⃣ Save ls output to file 2️⃣ Append date 3 times 3️⃣ Count lines using < 4️⃣ Create file using <<

14. Final Student Understanding

Redirection controls data flow  Saves time  Avoids manual typing  Very useful in scripting

HELPFUL COMMANDS IN LINUX (LECTURE STYLE)


1. Why Helpful Commands Are Important

In Linux:
  • Thousands of commands exist
  • No one can memorize all options
  • Linux provides built-in documentation
Helpful commands act as your Linux teacher

2. man Command (Manual Pages)

What is man?

man stands for manual It displays:
  • Command description
  • Syntax
  • Options
  • Examples

Syntax

man command_name

Example 1

man ls Shows:
  • NAME
  • SYNOPSIS
  • DESCRIPTION
  • OPTIONS

Output Structure

LS(1)                   User Commands                   LS(1) NAME ls - list directory contents SYNOPSIS ls [OPTION]... [FILE]... DESCRIPTION List information about the FILEs

Navigation in man Page

Key

Action

Enter

Next line

Space

Next page

b

Previous page

/word

Search

n

Next match

q

Quit


Example 2: Search inside man

man grep Inside man: /recursive

Example 3: Specific Section

man 5 passwd Section 5 → file formats

Man Sections

Section

Meaning

1

User commands

2

System calls

3

Library calls

4

Devices

5

File formats

8

Admin commands


3. help Command (Shell Built-ins)

What is help?

  • Shows help for shell built-in commands
  • Faster than man

Syntax

help help command

Example 1

help cd Output: cd: cd [-L|-P] [dir] Change the shell working directory.

Example 2

help exit

Difference: man vs help

man

help

External commands

Shell built-ins

Detailed

Short explanation

Uses pager

Instant output


4. info Command

What is info?

  • GNU documentation system
  • More structured than man

Syntax

info command

Example

info ls

Navigation Keys

Key

Action

n

Next

p

Previous

u

Up

q

Quit


Comparison

man

info

Short & quick

Detailed & structured


5. whatis Command

What is whatis?

  • One-line description of command

Syntax

whatis command

Example 1

whatis ls Output: ls (1) - list directory contents

Example 2

whatis chmod Output: chmod (1) - change file mode bits

When to Use

Quick reference  Interview preparation  Command recall

6. apropos Command

What is apropos?

  • Searches man page descriptions
  • Finds commands by keyword

Syntax

apropos keyword

Example 1

apropos copy Output: cp (1) - copy files and directories scp (1) - secure copy

Example 2

apropos network

7. type Command

What is type?

Shows:
  • Command type
  • Built-in / external / alias

Syntax

type command

Example 1

type cd Output: cd is a shell builtin

Example 2

type ls Output: ls is /usr/bin/ls

8. which Command

What is which?

  • Shows full path of command
  • Uses PATH variable

Syntax

which command

Example

which python Output: /usr/bin/python

9. whereis Command

What is whereis?

  • Finds binary, source, man pages

Syntax

whereis command

Example

whereis gcc Output: gcc: /usr/bin/gcc /usr/lib/gcc /usr/share/man/man1/gcc.1.gz

10. --help Option

What is --help?

Most commands support quick help

Syntax

command --help

Example 1

ls --help

Example 2

grep --help Shows:
  • Syntax
  • Options
  • Usage

11. Comparison Table (Quick Revision)

Command

Purpose

man

Full documentation

help

Shell built-ins

info

GNU docs

whatis

One-line info

apropos

Search commands

type

Command type

which

Command path

whereis

Binary + man

--help

Quick help


12. Real Student Workflow

1️⃣ Forgot command usage man command 2️⃣ Need quick syntax command --help 3️⃣ Find related command apropos keyword 4️⃣ Check built-in type command

14. Student Summary

Linux is self-documented  No need to memorize everything  man is your best friend  Helpful commands save time  Essential for Linux mastery LINUX TEXT VIEWING, SEARCHING & PROCESSING COMMANDS

(more, less, grep, pipe, sed – COMPLETE GUIDE)


1. more Command

What is more?

more is used to view file content page by page when the file is large.

Syntax

more filename

Example 1

more /etc/passwd Displays content one screen at a time

Example 2

ls -l /etc | more Output of ls viewed page by page

Example 3

ps aux | more Large process list readable

Important Keys in more

Key

Action

Space

Next page

Enter

Next line

q

Quit


Limitations of more

Cannot scroll backward  Limited search

2. less Command

What is less?

Advanced version of more  Scroll forward & backward

Syntax

less filename

Example 1

less /var/log/syslog

Example 2

ls -R / | less

Example 3

history | less

Useful Keys in less

Key

Action

Space

Next page

b

Previous page

/word

Search

n

Next match

q

Quit


Why less is better

Faster  Search support  Backward navigation

3. grep Command

What is grep?

Search text patterns inside files or output

Syntax

grep "pattern" file

Example 1

grep root /etc/passwd

Example 2

ps aux | grep ssh

Example 3

grep error logfile.txt

Common grep Options

-i (Ignore case)

grep -i linux file.txt

-n (Line number)

grep -n root /etc/passwd

-v (Invert match)

grep -v root /etc/passwd

-r (Recursive)

grep -r error /var/log

-w (Exact word)

grep -w user file.txt

-c (Count matches)

grep -c error logfile.txt

4. Pipe Operator |

What is Pipe?

Pass output of one command as input to another

Syntax

command1 | command2

Example 1

ls | more

Example 2

ps aux | grep root

Example 3

cat file.txt | wc -l

Multiple Pipes

ps aux | grep ssh | wc -l

Why Pipes are powerful

Avoid temporary files  Faster processing  Clean output

5. sed Command (Stream Editor)

What is sed?

Used to search, replace, delete, edit text without opening editor

Syntax

sed 'operation' filename

5.1 Replace Text

Example 1

sed 's/Linux/UNIX/' file.txt Replaces first occurrence per line

Replace all occurrences

sed 's/Linux/UNIX/g' file.txt

Case insensitive

sed 's/linux/UNIX/gi' file.txt

5.2 Delete Lines

Delete specific line

sed '3d' file.txt

Delete range

sed '2,5d' file.txt

Delete matching pattern

sed '/error/d' logfile.txt

5.3 Print Specific Lines

sed -n '5p' file.txt sed -n '2,6p' file.txt

5.4 Save Output to File

sed 's/old/new/g' file.txt > newfile.txt

5.5 Edit File Permanently (-i)

sed -i 's/old/new/g' file.txt ⚠ Be careful – modifies file directly

6. Combined Usage (Real-World Examples)

Example 1

grep error logfile.txt | less

Example 2

ps aux | grep root | sed 's/root/ADMIN/'

Example 3

cat file.txt | sed 's/test/demo/g' | grep demo

7. Command Comparison

Command

Purpose

more

Simple paging

less

Advanced paging

grep

Search text

pipe `

`

sed

Edit text


8. Student Practice Tasks

1️⃣ View large file using less 2️⃣ Search word ignoring case 3️⃣ Replace word using sed 4️⃣ Use pipe with grep 5️⃣ Count matching lines

9. Interview Important Notes

less preferred over more  grep + pipe very common  sed used in scripts  Pipes reduce memory usage

AWK COMMAND – COMPLETE LECTURE WITH OUTPUTS


1. What is AWK (Simple Explanation)

awk is a text processing tool used to:
  • Read a file line by line
  • Split each line into columns (fields)
  • Perform filtering, calculations, formatting
Think of AWK like Excel for text files.

2. Sample File Used for All Examples

Let us create a file called data.txt ID Name Marks 1 Ravi 85 2 Sita 90 3 Kumar 78 4 Anil 92

3. Basic AWK Syntax

awk '{ action }' filename

Example 1: Print entire file

awk '{print}' data.txt

Output

ID Name Marks 1 Ravi 85 2 Sita 90 3 Kumar 78 4 Anil 92 Same as cat, but processed line by line.

4. $0 – Print Complete Line

Command

awk '{print $0}' data.txt

Output

ID Name Marks 1 Ravi 85 2 Sita 90 3 Kumar 78 4 Anil 92 $0 means entire current line

5. $1, $2, $3 – Fields (Columns)

Variable

Meaning

$1

First column

$2

Second column

$3

Third column


Example 1: Print Names only

awk '{print $2}' data.txt

Output

Name Ravi Sita Kumar Anil

Example 2: Print ID and Marks

awk '{print 1,3}' data.txt

Output

ID Marks 1 85 2 90 3 78 4 92

6. NR – Line Number

Command

awk '{print NR, $0}' data.txt

Output

1 ID Name Marks 2 1 Ravi 85 3 2 Sita 90 4 3 Kumar 78 5 4 Anil 92 NR = record (line) number

Example: Print only 3rd line

awk 'NR==3 {print}' data.txt

Output

2 Sita 90

7. NF – Number of Fields

Command

awk '{print NF}' data.txt

Output

3 3 3 3 3 Each line has 3 columns

8. FS – Field Separator

Default separator = space

Example File: users.txt

root:x:0:0 ravi:x:1001:1001 sita:x:1002:1002

Command

awk 'BEGIN{FS=":"} {print $1}' users.txt

Output

root ravi sita FS=":" tells awk to split by colon

9. OFS – Output Field Separator


Command

awk 'BEGIN{OFS=" | "} {print 1,2,$3}' data.txt

Output

ID | Name | Marks 1 | Ravi | 85 2 | Sita | 90 3 | Kumar | 78 4 | Anil | 92

10. BEGIN Block (Pre-Processing)

Executed once before reading file

Command

awk 'BEGIN{print "Student Marks Report"} {print 2,3}' data.txt

Output

Student Marks Report Name Marks Ravi 85 Sita 90 Kumar 78 Anil 92

11. END Block (Post-Processing)

Executed once after file ends

Command

awk '{sum+=$3} END{print "Total Marks:", sum}' data.txt

Output

Total Marks: 345

12. Calculate Average

Command

awk '{sum+=$3} END{print "Average:", sum/(NR-1)}' data.txt

Output

Average: 86.25 (NR-1 because first line is header)

13. Conditional Statements


Example: Marks > 80

awk '$3>80 {print 2,3}' data.txt

Output

Ravi 85 Sita 90 Anil 92

14. Pattern Matching


Example: Find name "Sita"

awk '/Sita/ {print}' data.txt

Output

2 Sita 90

15. Multiple Conditions


Command

awk 'Misplaced &2!="Ravi" {print $2}' data.txt

Output

Sita Anil

16. FILENAME


Command

awk '{print FILENAME, NR, $0}' data.txt

Output

data.txt 1 ID Name Marks data.txt 2 1 Ravi 85 data.txt 3 2 Sita 90 data.txt 4 3 Kumar 78 data.txt 5 4 Anil 92

17. AWK with Pipe


Example

ls -l | awk '{print $9}'

Output

data.txt users.txt

18. Full AWK Program (BEGIN + BODY + END)

awk ' BEGIN { print "----Report Start----" } { print NR, 2,3 } END { print "----Report End----" } ' data.txt

Output

----Report Start---- 1 Name Marks 2 Ravi 85 3 Sita 90 4 Kumar 78 5 Anil 92 ----Report End----

19. Real-Time Use Case (Log Analysis)

log.txt

INFO server started ERROR disk full INFO user login ERROR memory low

Command

awk '/ERROR/ {print NR,$0}' log.txt

Output

2 ERROR disk full 4 ERROR memory low

20. Student Practice (Important)

1️⃣ Print only 2nd column 2️⃣ Print lines > 80 marks 3️⃣ Calculate total marks 4️⃣ Show line numbers 5️⃣ Change field separator

AWK OPERATORS – COMPLETE LECTURE WITH OUTPUTS

We will cover ALL AWK operators step by step:
  1. Arithmetic Operators
  2. Increment & Decrement Operators
  3. Assignment Operators
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Exponential Operator

Common Sample File (marks.txt)

ID Name Marks 1 Ravi 85 2 Sita 90 3 Kumar 78 4 Anil 92

1. Arithmetic Operators in AWK

Operator

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus


Example 1: Add 5 marks to everyone

awk '{if(NR>1) print 2,3+5}' marks.txt

Output

Ravi 90 Sita 95 Kumar 83 Anil 97

Example 2: Multiply marks by 2

awk '{if(NR>1) print 2,3*2}' marks.txt

Output

Ravi 170 Sita 180 Kumar 156 Anil 184

Example 3: Average marks

awk '{sum+=$3} END{print sum/(NR-1)}' marks.txt

Output

86.25

Example 4: Modulus (Even / Odd marks)

awk '{if(NR>1) print 2,3%2}' marks.txt

Output

Ravi 1 Sita 0 Kumar 0 Anil 0 1 = Odd, 0 = Even

2. Increment & Decrement Operators

Operator

Meaning

++

Increment by 1

--

Decrement by 1


Example 1: Increase marks by 1

awk '{if(NR>1){3++;print2,$3}}' marks.txt

Output

Ravi 86 Sita 91 Kumar 79 Anil 93

Example 2: Decrease marks by 1

awk '{if(NR>1){3;print2,$3}}' marks.txt

Output

Ravi 84 Sita 89 Kumar 77 Anil 91

Example 3: Line Counter using Increment

awk 'BEGIN{c=0} {c++} END{print c}' marks.txt

Output

5

3. Assignment Operators

Operator

Meaning

=

Assign

+=

Add and assign

-=

Subtract and assign

*=

Multiply and assign

/=

Divide and assign


Example 1: Add all marks

awk '{sum += $3} END{print sum}' marks.txt

Output

345

Example 2: Reduce marks by 10

awk '{if(NR>1){3=10;print2,$3}}' marks.txt

Output

Ravi 75 Sita 80 Kumar 68 Anil 82

Example 3: Double sum

awk '{sum += $3} END{sum *=2; print sum}' marks.txt

Output

690

4. Relational Operators

Operator

Meaning

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

==

Equal

!=

Not equal


Example 1: Marks greater than 80

awk '$3 > 80 {print 2,3}' marks.txt

Output

Ravi 85 Sita 90 Anil 92

Example 2: Marks equal to 90

awk '$3 == 90 {print $2}' marks.txt

Output

Sita

Example 3: Marks not equal to 78

awk '$3 != 78 {print 2,3}' marks.txt

Output

Ravi 85 Sita 90 Anil 92

5. Logical Operators

Operator

Meaning

&&

AND

!

NOT


Example 1: Marks >80 AND name not Ravi

awk 'Misplaced &2!="Ravi" {print 2,3}' marks.txt

Output

Sita 90 Anil 92

Example 2: Marks <80 OR name Kumar

awk '3<80||2=="Kumar" {print 2,3}' marks.txt

Output

Kumar 78

Example 3: NOT operator

awk '!($3>80) {print 2,3}' marks.txt

Output

Kumar 78

6. Ternary Operator

Syntax

condition ? true : false

Example 1: Pass / Fail

awk '{if(NR>1) print 2,(3>=80?"PASS":"FAIL")}' marks.txt

Output

Ravi PASS Sita PASS Kumar FAIL Anil PASS

Example 2: Grade system

awk '{if(NR>1) print 2,(3>=90?"A":($3>=80?"B":"C"))}' marks.txt

Output

Ravi B Sita A Kumar C Anil A

7. Exponential Operator (^ or **)


Example 1: Square of marks

awk '{if(NR>1) print 2,3^2}' marks.txt

Output

Ravi 7225 Sita 8100 Kumar 6084 Anil 8464

Example 2: Cube of marks

awk '{if(NR>1) print 2,3**3}' marks.txt

Output

Ravi 614125 Sita 729000 Kumar 474552 Anil 778688

8. Combined Operator Example (Real Life)

Command

awk '{if(NR>1){total+=$3; count++}} END{print "Average:", total/count}' marks.txt

Output

Average: 86.25

9. Key Points for Students

$3 += 5 means add 5 marks  && means both must be true  ?: replaces if-else  ^ used for power  ++ increases value by 1

DECISION MAKING STATEMENTS IN AWK

Decision-making statements are used to make decisions based on conditions. In AWK, we mainly use:
  1. if
  2. if–else
  3. if–else if–else
  4. Conditional expressions using relational & logical operators
  5. Ternary operator (short decision)

Sample Input File (student.txt)

ID Name Marks 1 Ravi 85 2 Sita 90 3 Kumar 78 4 Anil 92 5 Raju 60

1. IF Statement in AWK

Syntax

if (condition) action Executes action ONLY if condition is true

Example 1: Print students who passed (Marks ≥ 80)

awk '{if(3>=80)print2,$3}' student.txt

Output

Ravi 85 Sita 90 Anil 92

Example 2: Print students who failed (Marks < 80)

awk '{if(3<80)print2,"FAILED"}' student.txt

Output

Kumar FAILED Raju FAILED

Example 3: Skip header using IF

awk '{if(NR>1) print 2,3}' student.txt

Output

Ravi 85 Sita 90 Kumar 78 Anil 92 Raju 60

2. IF–ELSE Statement

Syntax

if (condition) action1 else action2 One condition → Two outcomes

Example 1: Pass / Fail

awk '{if(3>=80)print2,"PASS"; else print $2,"FAIL"}' student.txt

Output

Name FAIL Ravi PASS Sita PASS Kumar FAIL Anil PASS Raju FAIL

Example 2: Scholarship Eligibility

awk '{if(3>=90)print2,"Eligible"; else print $2,"Not Eligible"}' student.txt

Output

Ravi Not Eligible Sita Eligible Kumar Not Eligible Anil Eligible Raju Not Eligible

Example 3: Check Even or Odd Marks

awk '{if(32,"Even"; else print $2,"Odd"}' student.txt

Output

Ravi Odd Sita Even Kumar Even Anil Even Raju Even

3. IF – ELSE IF – ELSE Statement

Used when multiple conditions are needed.

Syntax

if (condition1) action1 else if (condition2) action2 else action3

Example 1: Grade System

awk '{ if(3>=90)print2,"Grade A" else if(3>=80)print2,"Grade B" else if(3>=70)print2,"Grade C" else print $2,"Fail" }' student.txt

Output

Name Fail Ravi Grade B Sita Grade A Kumar Grade C Anil Grade A Raju Fail

Example 2: Result Category

awk '{ if(3>=85)print2,"Distinction" else if(3>=60)print2,"First Class" else print $2,"Fail" }' student.txt

Output

Ravi Distinction Sita Distinction Kumar First Class Anil Distinction Raju First Class

4. Decision Making Using Logical Operators

Example 1: Marks >80 AND <90

awk '{if(Misplaced &3<90) print 2,3}' student.txt

Output

Ravi 85

Example 2: Marks <70 OR >90

awk '{if(3<70||3>90) print 2,3}' student.txt

Output

Anil 92 Raju 60

Example 3: NOT Operator

awk '{if(!(3>=80))print2,"Below Average"}' student.txt

Output

Kumar Below Average Raju Below Average

5. Nested IF (IF inside IF)

Example: Scholarship + Hostel Eligibility

awk '{ if($3>=80) { if(3>=90)print2,"Topper" else print $2,"Merit" } }' student.txt

Output

Ravi Merit Sita Topper Anil Topper

6. Ternary Operator (Short Decision Making)

Syntax

condition ? true : false

Example 1: Pass / Fail (Short Form)

awk '{print 2,(3>=80?"PASS":"FAIL")}' student.txt

Output

Name FAIL Ravi PASS Sita PASS Kumar FAIL Anil PASS Raju FAIL

Example 2: Grade Using Ternary

awk '{print 2,(3>=90?"A":($3>=80?"B":"C"))}' student.txt

Output

Name C Ravi B Sita A Kumar C Anil A Raju C

7. Decision Making in BEGIN and END Blocks

Example: Check file size

awk 'END{ if(NR>5) print "Large File" else print "Small File" }' student.txt

Output

Large File

8. Real-Time Example (Total Pass Count)

awk '{ if($3>=80) pass++ else fail++ } END{ print "Pass:",pass print "Fail:",fail }' student.txt

Output

Pass: 3 Fail: 2

KEY NOTES FOR STUDENTS

if → single condition  if–else → yes / no  else if → multiple decisions  Logical operators combine conditions  Ternary → short & fast decision

AWK LOOPS & LOOP CONTROL STATEMENTS

Loops are used when a set of statements must be executed repeatedly until a condition becomes false. In AWK, we have:
  1. while loop
  2. do–while loop
  3. for loop
  4. Loop control statements
  • break
  • continue
  • exit
  • next

Sample Input File (marks.txt)

ID Name Marks 1 Ravi 85 2 Sita 90 3 Kumar 78 4 Anil 92 5 Raju 60

1. WHILE LOOP

Syntax

while(condition) { statements } Loop runs as long as condition is TRUE

Example 1: Print numbers from 1 to 5

awk 'BEGIN{ i=1 while(i<=5) { print i i++ } }'

Output

1 2 3 4 5

Example 2: Print table of 2

awk 'BEGIN{ i=1 while(i<=10) { print "2 x",i,"=",2*i i++ } }'

Output

2 x 1 = 2 2 x 2 = 4 ... 2 x 10 = 20

Example 3: Sum of numbers 1 to 10

awk 'BEGIN{ i=1 sum=0 while(i<=10) { sum=sum+i i++ } print "Sum =",sum }'

Output

Sum = 55

2. DO–WHILE LOOP

Syntax

do { statements } while(condition) Executes AT LEAST ONCE, even if condition is false.

Example 1: Print 1 to 5

awk 'BEGIN{ i=1 do { print i i++ } while(i<=5) }'

Output

1 2 3 4 5

Example 2: Condition False but Runs Once

awk 'BEGIN{ i=10 do { print i } while(i<5) }'

Output

10 Important: Condition false, still printed once.

Example 3: Factorial using do–while

awk 'BEGIN{ n=5 fact=1 do { fact=fact*n n-- } while(n>0) print "Factorial =",fact }'

Output

Factorial = 120

3. FOR LOOP

Syntax

for(initialization; condition; increment) { statements } Most commonly used loop in AWK.

Example 1: Print numbers 1 to 10

awk 'BEGIN{ for(i=1;i<=10;i++) print i }'

Output

1 2 ... 10

Example 2: Sum of even numbers

awk 'BEGIN{ sum=0 for(i=2;i<=10;i+=2) sum+=i print "Sum =",sum }'

Output

Sum = 30

Example 3: Print file using for loop

awk '{ for(i=1;i<=NF;i++) print $i }' marks.txt

Output

ID Name Marks 1 Ravi 85 ...

Example 4: Print only names

awk 'NR>1{ for(i=2;i<=2;i++) print $i }' marks.txt

Output

Ravi Sita Kumar Anil Raju

4. FOR LOOP WITH ARRAYS

Example: Count Pass/Fail

awk 'NR>1{ if($3>=80) result["Pass"]++ else result["Fail"]++ } END{ for(i in result) print i,result[i] }' marks.txt

Output

Pass 3 Fail 2

5. LOOP CONTROL STATEMENTS


5.1 BREAK STATEMENT

Exits the loop immediately

Example 1: Stop at 5

awk 'BEGIN{ for(i=1;i<=10;i++) { if(i==6) break print i } }'

Output

1 2 3 4 5

Example 2: Stop after first fail

awk 'NR>1{ if(3<80)breakprint2,$3 }' marks.txt

Output

Ravi 85 Sita 90

5.2 CONTINUE STATEMENT

Skips current iteration only

Example 1: Skip number 5

awk 'BEGIN{ for(i=1;i<=10;i++) { if(i==5) continue print i } }'

Output

1 2 3 4 6 7 8 9 10

Example 2: Skip failed students

awk 'NR>1{ if(3<80)continueprint2,$3 }' marks.txt

Output

Ravi 85 Sita 90 Anil 92

5.3 NEXT STATEMENT

Skips current record and moves to next line

Example 1: Skip header

awk 'NR==1{next} {print 2,3}' marks.txt

Output

Ravi 85 Sita 90 Kumar 78 Anil 92 Raju 60

Example 2: Skip failed students

awk 'NR>1{ if(3<80)nextprint2,$3 }' marks.txt

Output

Ravi 85 Sita 90 Anil 92

5.4 EXIT STATEMENT

Stops entire AWK program

Example 1: Stop after 3 lines

awk 'NR==4{exit} {print}' marks.txt

Output

ID Name Marks 1 Ravi 85 2 Sita 90

Example 2: Exit when marks < 70

awk 'NR>1{ if(3<70)exitprint2,$3 }' marks.txt

Output

Ravi 85 Sita 90 Kumar 78 Anil 92

6. REAL-TIME COMBINED EXAMPLE

Top 3 students

awk 'NR>1{ if(count==3) exit if($3>=80) { print 2,3 count++ } }' marks.txt

Output

Ravi 85 Sita 90 Anil 92

IMPORTANT DIFFERENCES

Statement

Purpose

break

Exit loop only

continue

Skip iteration

next

Skip record

exit

Stop program


🎯 STUDENT TAKEAWAY

Use for loop mostly  Use while/do-while for conditions  Control flow using break, continue, next, exit  Combine with if conditions for real power

MAKEFILE – COMPLETE EXPLANATION (LECTURE STYLE)


1. What is a Makefile?

A Makefile is a special file that contains instructions (rules) used by the make command to:
  • Compile programs
  • Build executables
  • Automate repetitive tasks
  • Save time and avoid manual compilation errors
Makefile automates the build process

2. Why Do We Need a Makefile?

Without Makefile

gcc file1.c file2.c file3.c -o myapp Problems:
  • Long commands
  • Easy to make mistakes
  • Recompile all files even if one file changes
  • Not scalable for big projects

With Makefile

make Automatically compiles only modified files  Faster build  Industry standard  Used in Linux kernel, drivers, embedded systems, DevOps, CI/CD

3. Where Makefile is Used in Industry

Industry Area

Usage

Linux Kernel

Build kernel & drivers

Embedded Systems

Firmware compilation

DevOps

Automation pipelines

Software Companies

Large C/C++ projects

Open Source

Standard build system


4. What is make Command?

make reads Makefile and executes commands only when required make Automatically checks:
  • File timestamps
  • Dependencies
  • Rebuilds only changed parts

5. Basic Structure of a Makefile

target: dependencies <TAB> command ⚠ TAB is mandatory, not spaces

Example

hello: hello.c gcc hello.c -o hello

6. First Simple Example (Beginner)

hello.c

#include <stdio.h> int main() { printf("Hello Makefile "); return 0; }

Makefile

hello: hello.c gcc hello.c -o hello

Execution

make

Output

gcc hello.c -o hello ./hello

Program Output

Hello Makefile

7. How Makefile Works (Internally)

  1. make looks for file named Makefile
  2. Reads the first target
  3. Checks dependency timestamps
  4. If source is modified → recompiles
  5. Else → does nothing

8. Multiple Files Example (Real Industry Style)

Project Structure

project/ ├── main.c ├── add.c ├── sub.c ├── add.h ├── sub.h └── Makefile

main.c

#include <stdio.h> #include "add.h" #include "sub.h" int main() { printf("Add = %d ", add(5,3)); printf("Sub = %d ", sub(5,3)); return 0; }

add.c

int add(int a, int b) { return a + b; }

sub.c

int sub(int a, int b) { return a - b; }

Makefile (Without Variables)

myapp: main.o add.o sub.o gcc main.o add.o sub.o -o myapp main.o: main.c gcc -c main.c add.o: add.c gcc -c add.c sub.o: sub.c gcc -c sub.c

Execution

make

Output

gcc -c main.c gcc -c add.c gcc -c sub.c gcc main.o add.o sub.o -o myapp

Change only add.c

make

Output

gcc -c add.c gcc main.o add.o sub.o -o myapp Only modified file is compiled  Time-saving

9. Using Variables (Professional Way)

CC = gcc CFLAGS = -Wall -g myapp: main.o add.o sub.o (CC)main.oadd.osub.oomyappmain.o:main.c(CC) (CFLAGS)cmain.cadd.o:add.c(CC) (CFLAGS)cadd.csub.o:sub.c(CC) $(CFLAGS) -c sub.c

10. Automatic Variables (Important for Interviews)

Variable

Meaning

$@

Target name

$<

First dependency

$^

All dependencies


Optimized Makefile

CC = gcc CFLAGS = -Wall myapp: main.o add.o sub.o (CC)^ -o @(CC) (CFLAGS)c<

Advertisement

11. PHONY Targets (Industry Standard)

Targets that are not files

Example

.PHONY: clean clean: rm -f *.o myapp

Usage

make clean Removes object files  Very common in industry

12. Complete Industry-Level Makefile

CC = gcc CFLAGS = -Wall -g TARGET = myapp OBJ = main.o add.o sub.o (TARGET):(OBJ) (CC)(OBJ) -o (TARGET)(CC) (CFLAGS)c< clean: rm -f (OBJ)(TARGET)

13. Real Industry Workflow

1️⃣ Developer modifies code 2️⃣ Runs make 3️⃣ Only changed files compile 4️⃣ Faster CI/CD pipeline 5️⃣ Used in Git, Jenkins, Docker

14. Common Mistakes (Students Should Know)

Using spaces instead of TAB  Forgetting dependencies  Not using variables  Not adding clean target

15. Makefile Interview Questions

What is Makefile?  Difference between make & gcc?  What is @,<, $^?  What is .PHONY?  How make improves build time?

17. Student Summary

Makefile automates compilation  Used in real companies  Saves time & avoids errors  Essential for Linux programmers  Must-know for interviews

INTRODUCTION TO TCL (Tool Command Language)


1. What is TCL?

TCL stands for Tool Command Language

TCL is:

  • A high-level scripting language
  • Interpreted (not compiled)
  • Very simple syntax
  • Designed for command execution and automation

Created by John Ousterhout


2. Why TCL is Popular (Key Features)

✔ Easy to learn
✔ Powerful string handling
✔ Strong scripting capability
✔ Platform independent
✔ Widely used in
EDA tools


3. Real-Time Applications of TCL

TCL is heavily used in industry, especially where automation is required.

Major Real-Time Uses

1️⃣ EDA / VLSI Industry

  • Synopsys (Design Compiler, PrimeTime)
  • Cadence
  • Mentor Graphics

Used for:

  • Timing analysis
  • Synthesis scripts
  • Physical design automation

2️⃣ Automation Scripts

  • File handling
  • Log parsing
  • Batch execution

3️⃣ Embedded Systems

  • Testing automation
  • Configuration scripts

4️⃣ GUI Applications

TCL + Tk → GUI programs


Industry Example

ASIC Engineer writes TCL script → Tool reads TCL → Tool executes commands → Reports generated automatically

4. Basic Structure of a TCL Script

command argument1 argument2

✔ No semicolon required
✔ One command per line


Example

puts "Hello TCL"

Output:

Hello TCL

5. TCL Variables

Important Rule

TCL variables are NOT typed
Everything is a string


6. How to Set a Variable (set command)

Syntax

set variable_name value

Example 1: Simple Variable

set a 10 puts $a

Output:

10

Example 2: String Variable

set name "Linux TCL" puts $name

Output:

Linux TCL

Important Rule

✔ $ is used to access variable value ✔ set is used to assign value

Example 3: Reassign Variable

set x 5 set x 20 puts $x

Output:

20

7. Variable Substitution in TCL

TCL performs substitution BEFORE execution

Types of Substitution

1️⃣ Variable substitution ($) 2️⃣ Command substitution ([]) 3️⃣ Backslash substitution ()

8. Variable Substitution ($) – Deep Explanation

Example 1

set a 5 set b 10 puts aputsb

Output:

5 10

Example 2: Using Variable in Sentence

set name Rahul puts "My name is $name"

Output:

My name is Rahul

Wrong Way

puts 'My name is $name'

Output:

My name is $name

Single quotes do NOT substitute variables


9. Command Substitution ([ ]) – VERY IMPORTANT

What is Command Substitution?

Execute a command first
Use its output as value


Syntax

set var [command]

Example 1: expr Command

set x [expr 5 + 3] puts $x

Output:

8

Example 2: Without Command Substitution

set x expr 5 + 3 puts $x

Output:

expr

Wrong result


Example 3: Nested Command Substitution

set y [expr [expr 2 + 3] * 4] puts $y

Output:

20

10. expr Command (Arithmetic in TCL)

Syntax

expr expression

Example 1

set a 10 set b 5 set sum [expr a+b] puts $sum

Output:

15

Example 2: Multiplication

set result [expr 4 * 6] puts $result

Output:

24

Example 3: Division

puts [expr 10 / 2]

Output:

5

11. Difference Between {} and "" in TCL

Double Quotes " "

✔ Variable substitution
✔ Command substitution

set a 10 puts "Value is $a"

Output:

Value is 10

Curly Braces { }

No substitution
✔ Faster execution

puts {Value is $a}

Output:

Value is $a

Best Practice

  • Use {} when no substitution needed
  • Use "" when substitution required

12. Backslash Substitution (\)

Used for:

  • New line
  • Tab
  • Escape characters

Example 1

puts "Hello TCL"

Output:

Hello TCL

Example 2

puts "Name: Rahul"

Output:

Name:   Rahul

13. Real-Time Example (Automation Script)

set file_count [exec ls | wc -l] puts "Total files: $file_count"

Output:

Total files: 12

Used in:

  • Build systems
  • Verification flows
  • Reports generation

14. Common Mistakes Students Make

Forgetting $  Not using [ ] for expr  Using single quotes  Mixing {} and ""

15. TCL Summary (Exam + Industry)

✔ Everything is a command ✔ Variables are strings ✔ $ → variable substitution ✔ [ ] → command substitution ✔ {} → no substitution ✔ expr → arithmetic

TCL COMMANDS – DETAILED EXPLANATION

Commands Covered

  1. puts
  2. gets
  3. split
  4. join
  5. expr
  • Arithmetic operators
  • Relational operators
  • Logical operators

1. puts Command

What is puts?

puts is used to print output on the screen or write output to a file.

Syntax

puts "message" puts variable

Example 1: Simple Output

puts "Welcome to TCL"

Output:

Welcome to TCL

Example 2: Printing Variable

set name Linux puts $name

Output:

Linux

Example 3: With Variable Substitution

set x 10 puts "Value of x is $x"

Output:

Value of x is 10

Example 4: Without New Line

puts -nonewline "Enter name: "

Output:

Enter name:

Used in user input programs


2. gets Command

What is gets?

gets is used to take input from the user or read input from a file.

Syntax

gets stdin variable

Example 1: Basic Input

puts -nonewline "Enter your name: " gets stdin name puts "Hello $name"

Input:

Rahul

Output:

Hello Rahul

Example 2: Input and Arithmetic

puts "Enter first number:" gets stdin a puts "Enter second number:" gets stdin b puts "Sum = [expr a+b]"

Input:

5 3

Output:

Sum = 8

Example 3: Input Validation Style

puts "Enter age:" gets stdin age puts "Your age is $age"

Used in interactive scripts


3. split Command

What is split?

split is used to convert a string into a list based on a delimiter.

Syntax

split string delimiter

Example 1: Split by Space

set str "Linux TCL Shell" set result [split str""]putsresult

Output:

Linux TCL Shell

Internally stored as:

{Linux} {TCL} {Shell}

Example 2: Split by Comma

set data "10,20,30" set nums [split data","]putsnums

Output:

10 20 30

Example 3: Access Split Values

set str "A:B:C" set list [split str":"]puts[lindexlist 0] puts [lindex list1]puts[lindexlist 2]

Output:

A B C

4. join Command

What is join?

join is used to convert a list into a string using a delimiter.

Syntax

join list delimiter

Example 1: Join with Space

set list {Linux TCL Script} puts [join $list " "]

Output:

Linux TCL Script

Example 2: Join with Comma

set nums {10 20 30} puts [join $nums ","]

Output:

10,20,30

Example 3: File Path Example

set path {/home user docs} puts [join $path "/"]

Output:

/home/user/docs

Real-time use: Path creation


5. expr Command (MOST IMPORTANT)

expr is used to evaluate expressions.

Syntax

expr expression

5.1 Arithmetic Operators

Operator

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus


Example 1: Addition

puts [expr 5 + 3]

Output:

8

Example 2: Multiple Variables

set a 10 set b 4 puts [expr ab]

Output:

6

Example 3: Modulus

puts [expr 10 % 3]

Output:

1

5.2 Relational Operators

Operator

Meaning

==

Equal

!=

Not equal

>

Greater

<

Less

>=

Greater or equal

<=

Less or equal

Output: 1 (true) or 0 (false)

Example 1

puts [expr 5 > 3]

Output:

1

Example 2

puts [expr 5 == 10]

Output:

0

Example 3: Using Variables

set x 20 set y 10 puts [expr x<=y]

Output:

0

5.3 Logical Operators

Operator

Meaning

&&

AND

!

NOT


Example 1: AND

puts [expr (5 > 3) && (10 > 5)]

Output:

1

Example 2: OR

puts [expr (5 > 10) || (3 < 7)]

Output:

1

Example 3: NOT

puts [expr !(5 > 10)]

Output:

1

6. Real-Time Example (Decision Making Base)

puts "Enter marks:" gets stdin marks if {[expr $marks >= 50]} { puts "PASS" } else { puts "FAIL" }

Input:

65

Output:

PASS

7. Summary Table (Quick Revision)

Command

Purpose

puts

Print output

gets

Take input

split

String → list

join

List → string

expr

Calculations & conditions


TCL MATH FUNCTIONS – COMPLETE & DEEP EXPLANATION

In TCL, mathematical functions are mainly used inside the expr command.

General Rule

All math functions are written inside expr

Syntax

expr function(value)

or

expr {function(value)} Using { } is recommended (safe & faster)

1. abs() – Absolute Value

What is abs()?

Returns the positive value of a number (removes sign).


Example 1

puts [expr {abs(-10)}]

Output:

10

Example 2

puts [expr {abs(25)}]

Output:

25

Example 3 (Real Use)

set balance -500 puts "Final amount = [expr {abs($balance)}]"

Output:

Final amount = 500

Used in banking & difference calculations


2. ceil() – Ceiling Value

What is ceil()?

Rounds UP to the nearest integer.


Example 1

puts [expr {ceil(4.2)}]

Output:

5

Example 2

puts [expr {ceil(7.0)}]

Output:

7

Example 3 (Real Use)

set pages 3.1 puts "Total pages = [expr {ceil($pages)}]"

Output:

Total pages = 4

Used in billing & resource allocation


3. floor() – Floor Value

What is floor()?

Rounds DOWN to the nearest integer.


Example 1

puts [expr {floor(4.9)}]

Output:

4

Example 2

puts [expr {floor(10.1)}]

Output:

10

Example 3 (Real Use)

set price 99.99 puts "Rounded price = [expr {floor($price)}]"

Output:

99

4. double() – Convert to Floating Point

What is double()?

Converts a number into floating-point (decimal).


Example 1

puts [expr {double(5)}]

Output:

5.0

Example 2

set x 10 puts [expr {double($x)/3}]

Output:

3.3333333333333335

Important for accurate division


Without double

puts [expr {10/3}]

Output:

3

⚠️ Integer division


5. int() – Convert to Integer

What is int()?

Removes the decimal part and keeps integer.


Example 1

puts [expr {int(5.9)}]

Output:

5

Example 2

puts [expr {int(-4.7)}]

Output:

-4

Example 3 (Real Use)

set marks 89.6 puts "Final marks = [expr {int($marks)}]"

Output:

Final marks = 89

6. min() – Minimum Value

What is min()?

Returns the smallest value.


Example 1

puts [expr {min(10, 20)}]

Output:

10

Example 2

puts [expr {min(5, -3, 7)}]

Output:

-3

Example 3 (Real Use)

set a 15 set b 9 puts "Lowest value = [expr {min(a,b)}]"

Output:

Lowest value = 9

7. max() – Maximum Value

What is max()?

Returns the largest value.


Example 1

puts [expr {max(10, 20)}]

Output:

20

Example 2

puts [expr {max(5, -3, 7)}]

Output:

7

Example 3 (Real Use)

set score1 85 set score2 92 puts "Top score = [expr {max(score1,score2)}]"

Output:

Top score = 92

8. pow() – Power Function

What is pow()?

Calculates base raised to power.


Example 1

puts [expr {pow(2,3)}]

Output:

8.0

Example 2

puts [expr {pow(5,2)}]

Output:

25.0

Example 3 (Real Use)

set radius 3 puts "Area = [expr {3.14 * pow($radius,2)}]"

Output:

Area = 28.26

Used in engineering & scientific calculations


9. Combined Example (Real-Time Script)

puts "Enter a number:" gets stdin num puts "Absolute = [expr {abs($num)}]" puts "Ceil      = [expr {ceil($num)}]" puts "Floor     = [expr {floor($num)}]" puts "Square    = [expr {pow($num,2)}]"

Input:

-4.6

Output:

Absolute = 4.6 Ceil      = -4 Floor     = -5 Square    = 21.16

10. Quick Reference Table

Function

Purpose

abs()

Absolute value

ceil()

Round up

floor()

Round down

double()

Convert to float

int()

Convert to integer

min()

Smallest value

max()

Largest value

pow()

Power calculation


TCL LISTS – COMPLETE & IN-DEPTH EXPLANATION


1. What is a List in TCL?

A list is a collection of elements stored in order.

Elements can be:

  • Numbers
  • Strings
  • Variables
  • Even other lists

Creating a List

set mylist {10 20 30 40}

Printing a List

puts $mylist

Output:

10 20 30 40

Another Example

set names {Ravi Kumar Sita Mohan} puts $names

Output:

Ravi Kumar Sita Mohan

2. llength – Length of List

What is llength?

Returns the number of elements in a list.


Syntax

llength list_name

Example 1

set list1 {a b c d} puts [llength $list1]

Output:

4

Example 2

set marks {85 90 78 92} puts "Total students = [llength $marks]"

Output:

Total students = 4

Example 3 (Nested List)

set list2 {{a b} {c d}} puts [llength $list2]

Output:

2

3. lindex – Access Element by Index

What is lindex?

Returns the element at a specific index.

Index starts from 0


Syntax

lindex list_name index

Example 1

set fruits {apple banana mango} puts [lindex $fruits 0]

Output:

apple

Example 2

puts [lindex $fruits 2]

Output:

mango

Example 3 (Nested List)

set data {{10 20} {30 40}} puts [lindex $data 1]

Output:

30 40

Example 4 (Nested Inside Nested)

puts [lindex [lindex $data 1] 0]

Output:

30

4. lappend – Add Element to List

What is lappend?

Adds elements at the end of a list.


Syntax

lappend list_name element

Example 1

set list1 {1 2 3} lappend list1 4 puts $list1

Output:

1 2 3 4

Example 2 (Multiple Elements)

lappend list1 5 6 puts $list1

Output:

1 2 3 4 5 6

Example 3 (Real Use)

set students {} lappend students Ravi Sita Mohan puts $students

Output:

Ravi Sita Mohan

5. lset – Modify List Element

What is lset?

Replaces an element at a given index.


Syntax

lset list_name index new_value

Example 1

set colors {red blue green} lset colors 1 yellow puts $colors

Output:

red yellow green

Example 2

set nums {10 20 30} lset nums 2 100 puts $nums

Output:

10 20 100

Example 3 (Nested List)

set matrix {{1 2} {3 4}} lset matrix 1 1 99 puts $matrix

Output:

{1 2} {3 99}

6. lsort – Sort a List

What is lsort?

Sorts elements in ascending order (default).


Syntax

lsort list_name

Example 1 (Numbers)

set nums {5 2 9 1} puts [lsort $nums]

Output:

1 2 5 9

Example 2 (Strings)

set names {Ravi Anil Sita Mohan} puts [lsort $names]

Output:

Anil Mohan Ravi Sita

Example 3 (Descending Order)

puts [lsort -decreasing $nums]

Output:

9 5 2 1

Example 4 (Numeric Sort)

set values {10 2 30} puts [lsort -integer $values]

Output:

2 10 30

7. lsearch – Search Element in List

What is lsearch?

Returns the index of an element.

Returns -1 if not found

Syntax

lsearch list_name value

Example 1

set fruits {apple banana mango} puts [lsearch $fruits banana]

Output:

1

Example 2 (Not Found)

puts [lsearch $fruits orange]

Output:

-1

Example 3 (Pattern Search)

set files {file1.txt file2.log file3.txt} puts [lsearch -glob $files *.txt]

Output:

0

Example 4 (All Matches)

set nums {10 20 10 30 10} puts [lsearch -all $nums 10]

Output:

0 2 4

8. Combined Real-Time Example

set students {Ravi Sita Mohan} lappend students Anil puts "Students: students"puts"Total:[llengthstudents]" puts "First student: [lindex students0]"puts"Sortedlist:[lsortstudents]"

Output:

Students: Ravi Sita Mohan Anil Total: 4 First student: Ravi Sorted list: Anil Mohan Ravi Sita

9. Quick Summary Table

Command

Purpose

llength

Count elements

lindex

Get element

lappend

Add element

lset

Modify element

lsort

Sort list

lsearch

Search element


TCL LOOPS – COMPLETE & IN-DEPTH EXPLANATION


1. What is a Loop?

A loop is used to repeat a block of code multiple times until a condition is met.

Why loops?

  • Avoid writing same code again and again
  • Process lists, files, numbers
  • Automate real-time tasks (industry scripts)

Types of Loops in TCL

Loop

Used for

for

Known number of iterations

while

Loop based on condition

foreach

Loop over list elements


2. FOR LOOP

Syntax

for {initialization} {condition} {increment} { statements }

How for loop works

1️⃣ Initialization runs once
2️⃣ Condition checked
3️⃣ Body executes
4️⃣ Increment runs
5️⃣ Repeat until condition fails


Example 1: Print numbers 1 to 5

for {set i 1} {$i <= 5} {incr i} { puts $i }

Output:

1 2 3 4 5

Example 2: Print even numbers

for {set i 2} {$i <= 10} {incr i 2} { puts $i }

Output:

2 4 6 8 10

Example 3: Table of 5

for {set i 1} {$i <= 10} {incr i} { puts "5 x i=[expr5i]" }

Output:

5 x 1 = 5 5 x 2 = 10 ... 5 x 10 = 50

Example 4: Real-time Script (File creation)

for {set i 1} {$i <= 3} {incr i} { puts "Creating file$i.txt" }

Output:

Creating file1.txt Creating file2.txt Creating file3.txt

3. WHILE LOOP

Syntax

while {condition} { statements }

How while loop works

✔ Condition checked first
✔ Loop runs
only if condition is true


Example 1: Print numbers 1 to 5

set i 1 while {$i <= 5} { puts $i incr i }

Output:

1 2 3 4 5

Example 2: Countdown

set n 5 while {$n > 0} { puts "Countdown: $n" incr n -1 }

Output:

Countdown: 5 Countdown: 4 ... Countdown: 1

Example 3: Sum of numbers

set i 1 set sum 0 while {Extra close brace or missing open bracesum"

Output:

Sum = 15

Real-time Use

✔ Unknown number of iterations
✔ Log monitoring
✔ Waiting for condition


4. FOREACH LOOP (MOST IMPORTANT)

Syntax

foreach variable list { statements }

Why foreach is powerful

  • Best for lists
  • Clean & readable
  • Widely used in industry TCL scripts

Example 1: Print list elements

set fruits {apple banana mango} foreach f $fruits { puts $f }

Output:

apple banana mango

Example 2: Sum of list values

set nums {10 20 30} set sum 0 foreach n numssetsum[expr$sum+$n]puts"Total=sum"

Output:

Total = 60

Example 3: Index + Value

set students {Ravi Sita Mohan} set i 0 foreach s $students { puts "Index i=s" incr i }

Output:

Index 0 = Ravi Index 1 = Sita Index 2 = Mohan

Example 4: Multiple variables

foreach {name age} {Ravi 25 Sita 23 Mohan 28} { puts "nameisage years old" }

Output:

Ravi is 25 years old Sita is 23 years old Mohan is 28 years old

Example 5: Nested foreach

set matrix {{1 2} {3 4}} foreach row $matrix { foreach val $row { puts $val } }

Output:

1 2 3 4

5. SAME APPLICATION USING DIFFERENT LOOPS

Application: Print numbers 1 to 3

Using for

for {set i 1} {$i <= 3} {incr i} { puts $i }

Using while

set i 1 while {$i <= 3} { puts $i incr i }

Using foreach

foreach i {1 2 3} { puts $i }

Output (Same for all):

1 2 3

6. Loop Control Commands

break – Exit loop

for {set i 1} {$i <= 5} {incr i} { if {Extra close brace or missing open bracei }

Output:

1 2

continue – Skip iteration

for {set i 1} {$i <= 5} {incr i} { if {Extra close brace or missing open bracei }

Output:

1 2 4 5

7. Real-Time Industry Script Example

Check list of servers

set servers {server1 server2 server3} foreach s $servers { puts "Checking $s..." }

Output:

Checking server1... Checking server2... Checking server3...

8. Quick Comparison Table

Feature

for

while

foreach

Known count

Condition-based

List handling

✔ BEST

Industry use

Medium

Medium

High


TCL LOOP CONTROL STATEMENTS

Loop control statements are used to change the normal flow of loops.

In TCL, we mainly use:

  1. break
  2. continue

1. break Statement

What is break?

  • break is used to immediately stop the loop
  • Control comes outside the loop
  • Remaining iterations are skipped

Script 1: Using break in a loop

for {set i 1} {$i <= 5} {incr i} { if {Extra close brace or missing open bracei" } puts "Loop ended"

Execution Flow

  • i = 1 → printed
  • i = 2 → printed
  • i = 3 → condition true → break → loop stops

Output

Value: 1 Value: 2 Loop ended

Real-Time Example (Industry use)

Stop checking servers when failure found

set servers {srv1 srv2 fail_srv srv3} foreach s $servers { if {Extra close brace or missing open braces" }

Output

Checking srv1 Checking srv2 Error found on fail_srv

2. continue Statement

What is continue?

  • continue skips the current iteration
  • Loop continues with next iteration
  • Loop does NOT stop

Script 2: Using continue in a loop

for {set i 1} {$i <= 5} {incr i} { if {Extra close brace or missing open bracei" } puts "Loop completed"

Execution Flow

  • i = 1 → printed
  • i = 2 → printed
  • i = 3 → skipped
  • i = 4, 5 → printed

Output

Value: 1 Value: 2 Value: 4 Value: 5 Loop completed

Real-Time Example (Skip invalid data)

set data {10 20 -1 30} foreach d $data { if {Extra close brace or missing open braced" }

Output

Valid value: 10 Valid value: 20 Valid value: 30

3. Difference Between break and continue

Feature

break

continue

Stops loop

Yes

No

Skips iteration

No

Yes

Control

Goes outside loop

Goes to next iteration


Summary for Students

  • Use break → when you want to exit loop completely
  • Use continue → when you want to skip unwanted values
  • Very useful in data validation, error handling, automation scripts

DECISION MAKING IN TCL

Decision-making statements allow a program to take decisions based on conditions.

In TCL, decision making is done using:

  1. if
  2. if…else
  3. if…elseif…else
  4. switch

1. if Statement

Purpose

  • Executes a block only when condition is TRUE
  • No action when condition is FALSE

Syntax

if {condition} { statements }

Script 1: Simple if

set age 20 if {$age >= 18} { puts "Eligible to vote" }

Explanation

  • Condition: age >= 18
  • True → block executed

Output

Eligible to vote

Real-Time Use

Checking permission before running a task

set isAdmin 1 if {$isAdmin} { puts "Access granted" }

2. if … else Statement

Purpose

  • Executes one block if condition is TRUE
  • Executes alternate block if FALSE

Syntax

if {condition} { statements } else { statements }

Script 2: if…else

set marks 45 if {$marks >= 50} { puts "Pass" } else { puts "Fail" }

Explanation

  • marks < 50 → else block executed

Output

Fail

Real-Time Example

File existence check

set file "data.txt" if {[file exists $file]} { puts "File exists" } else { puts "File not found" }

3. if … elseif … else Statement

Purpose

  • Used when multiple conditions need checking
  • Executes only one matching block

Syntax

if {cond1} { statements } elseif {cond2} { statements } else { statements }

Script 3: Grade System

set marks 78 if {$marks >= 85} { puts "Grade A" } elseif {$marks >= 60} { puts "Grade B" } elseif {$marks >= 40} { puts "Grade C" } else { puts "Fail" }

Explanation

  • marks = 78 → second condition true

Output

Grade B

Real-Time Example

Server load decision

set load 65 if {$load > 80} { puts "High load" } elseif {$load > 50} { puts "Medium load" } else { puts "Low load" }

4. switch Statement

Purpose

  • Used for fixed value comparisons
  • Cleaner than multiple elseif

Syntax

switch value { pattern1 { statements } pattern2 { statements } default  { statements } }

Script 4: Menu Selection

set choice 2 switch $choice { 1 { puts "Start" } 2 { puts "Stop" } 3 { puts "Restart" } default { puts "Invalid option" } }

Explanation

  • choice = 2 → matched case 2

Output

Stop

Real-Time Example

Day based action

set day "Mon" switch $day { "Mon" { puts "Work day" } "Sat" { puts "Weekend" } "Sun" { puts "Holiday" } default { puts "Invalid day" } }

Comparison: if vs switch

Feature

if / elseif

switch

Range checking

Yes

No

Exact match

Not ideal

Best

Readability

Medium

High


Final Summary for Students

  • Use if → single condition
  • Use if…else → yes / no decision
  • Use if…elseif…else → multiple conditions
  • Use switch → fixed value matching
  • Decision making is core logic of automation scripts

TCL PROCEDURES (proc)

(Industrial-Level Explanation)


1. What is a Procedure (proc) in TCL?

A procedure is a reusable block of code that:

  • Performs a specific task
  • Can accept inputs (arguments)
  • Can return a value
  • Helps in modular, readable, maintainable scripts
In industry, 90% of large TCL scripts use proc.

2. Why Procedures Are Used (Industry View)

Reason

Explanation

Code reuse

Avoid repeating code

Maintenance

Change once, effect everywhere

Readability

Script becomes clean

Debugging

Easy to test functions

Automation

Used in EDA, DevOps, CI pipelines


3. Basic Syntax of proc

proc procedure_name {arguments} { statements return value }

4. Script 1: Simple Procedure (No Arguments)

proc greet {} { puts "Welcome to TCL programming" } greet

Output

Welcome to TCL programming

Used for common startup messages


5. Script 2: Procedure with One Argument

proc sayHello {name} { puts "Hello $name" } sayHello "Rahul"

Output

Hello Rahul

Used in user-specific automation


6. Script 3: Procedure with Multiple Arguments

proc add {a b} { set sum [expr {a+b}] puts "Sum is $sum" } add 10 20

Output

Sum is 30

Used in EDA calculations / reports


7. Script 4: Procedure with Return Value

proc square {n} { return [expr {nn}] } set result [square 5] puts "Square = $result"

Output

Square = 25

Return sends value back to caller


8. Script 5: Real-Time File Check Procedure

proc checkFile {filename} { if {[file exists $filename]} { return "File exists" } else { return "File not found" } } puts [checkFile "data.txt"]

Output

File not found

Used in build & deployment scripts


9. Script 6: Procedure with Default Arguments

proc greetUser {{name "Guest"}} { puts "Welcome $name" } greetUser greetUser "Admin"

Output

Welcome Guest Welcome Admin

Used in optional input handling


10. Script 7: Industrial Logging Procedure

proc logMessage {level msg} { set time [clock format [clock seconds]] puts "time[level] $msg" } logMessage INFO "Build started" logMessage ERROR "File missing"

Output

Mon Jan 8 10:30:20 2026 [INFO] Build started Mon Jan 8 10:30:20 2026 [ERROR] File missing

Used in EDA tools, CI/CD logs


11. Script 8: Mathematical Utility Procedure

proc average {a b c} { return [expr {(a+b + $c) / 3.0}] } puts "Average = [average 10 20 30]"

Output

Average = 20.0

Used in data analysis scripts


12. Script 9: Loop Inside Procedure

proc printNumbers {n} { for {set i 1} {i<=n} {incr i} { puts $i } } printNumbers 5

Output

1 2 3 4 5

Used in batch processing


13. Script 10: Real Industrial Automation Script

Task

✔ Read file
✔ Count lines
✔ Return count

proc countLines {filename} { if {![file exists Extra close brace or missing open bracefilename r] set count 0 while {[gets Extra close brace or missing open bracefp return $count } set lines [countLines "data.txt"] if {$lines == -1} { puts "File not found" } else { puts "Total lines: $lines" }

Output

Total lines: 15

Very common in EDA verification flows


14. Important Industry Rules for proc

✔ Always use meaningful names ✔ Keep procedures small & single-purpose ✔ Always use return ✔ Avoid global variables (use arguments) ✔ Add comments in production scripts

15. Common Mistakes Students Make

Forgetting {} in arguments  Not returning values  Using global variables unnecessarily  Writing too much logic in one procedure

Final Student Summary

  • proc = reusable function
  • Arguments pass data
  • return sends result
  • Used heavily in EDA, automation, DevOps
  • Industry TCL scripts are procedure-driven
Advertisement
Advertisement