0% found this document useful (0 votes)
1 views62 pages

UNIX Shell Programming - Complete Question Bank Solutions

The document is a comprehensive question bank on UNIX Shell Programming, covering various modules including introduction, file system, editors, shell programming, and processes. It provides detailed explanations, commands, and examples for user management, file system organization, and key UNIX commands. Additionally, it discusses the architecture of UNIX, internal and external commands, and standards like POSIX and SUS.

Uploaded by

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

UNIX Shell Programming - Complete Question Bank Solutions

The document is a comprehensive question bank on UNIX Shell Programming, covering various modules including introduction, file system, editors, shell programming, and processes. It provides detailed explanations, commands, and examples for user management, file system organization, and key UNIX commands. Additionally, it discusses the architecture of UNIX, internal and external commands, and standards like POSIX and SUS.

Uploaded by

Raghav Purohit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIX Shell Programming — Question Bank

Solutions
Complete solutions for all 54 questions (Modules 1–5) | 22CB461

Table of Contents

Module 1 — Introduction & Basics Module 4 — Shell Programming

Module 2 — File System Module 5 — Processes, Scheduling & Perl

Module 3 — Editors, RE & Redirection

Module 1 INTRODUCTION & BASICS

1 Explain the architecture of UNIX. Describe the relationship between the shell and
the kernel, and explain the UNIX environment highlighting key components (file
system, processes, user interfaces) and features.

UNIX Architecture

UNIX follows a layered architecture:

1. Hardware — CPU, memory, disk, I/O devices.

2. Kernel — Core of the OS; manages hardware, memory, processes, file system, and device
drivers.

3. Shell — Command-line interpreter that acts as the interface between the user and the kernel.

4. System Utilities / Tools — Programs like ls , grep , awk , sed , compilers, etc.

5. Application Programs — User-level software (DBMS, Mail, FTP, browsers).

Shell–Kernel Relationship

The user enters commands in the shell. The shell reads the input, interprets it, and passes it to the
kernel. The kernel executes the command and returns the result to the shell, which then displays it
to the user.

Key Components of UNIX Environment


User Interface (Shell) — Bourne Shell ( sh ), C Shell ( csh ), Korn Shell ( ksh ), Bash
( bash ).

Command Structure — command [options] [arguments]

File System Environment — Hierarchical tree starting at root / with directories like /bin ,
/etc , /home , /usr , /dev , /tmp , /var .

Environment Variables — PATH (command search path), HOME (user’s home directory),
USER (current user).

Processes — Every program in execution is a process; the kernel schedules and manages
them.

Utilities & Tools — File handling ( cp , mv , rm ), text processing ( grep , awk , sed ),
process control ( ps , kill , top ).

Features of UNIX

Multiuser system

Multitasking system

Building-block approach (small tools combined for complex tasks)

Pattern matching (wildcards, regular expressions)

Programming facility (shell scripting)

Extensive documentation ( man pages)

2 Explain user management in UNIX (add, modify, delete).

User management in UNIX is performed by the superuser (root) using the following commands:

1. Adding a User — useradd

sudo useradd -m -s /bin/bash -c "Alice Smith" alice


sudo passwd alice

Options: -m creates home directory, -s sets shell, -c adds GECOS info, -u specifies UID, -
g specifies primary group.

2. Modifying a User — usermod

sudo usermod -l alicia alice # rename user


sudo usermod -s /bin/zsh alicia # change shell
sudo usermod -aG developers alicia # add to supplementary group

3. Deleting a User — userdel


sudo userdel alice # delete user (keep home)
sudo userdel -r alice # delete user and home directory

Verification

id alice
whoami

3 Explain /etc/passwd and /etc/shadow . /etc/shadow more secure?


the Why Give examples
purpose is of entries.
of

/etc/passwd

Stores user account information. Each line has 7 colon-separated fields:

username:password:UID:GID:GECOS:home_directory:shell

Example:

root:x:0:0:root:/root:/bin/bash
alice:x:1001:1001:Alice:/home/alice:/bin/bash

The x in the password field indicates the encrypted password is stored in /etc/shadow .

/etc/shadow

Stores encrypted passwords and password-aging info. Each line has 9 fields:

username:encrypted_password:last_change:min:max:warn:inactive:expire:reserved

Example:

alice:$6$rounds=5000$saltsalt$hash...:19000:0:99999:7:::

Why /etc/shadow is More Secure

It is readable only by root (permissions 000 or 640 ), whereas /etc/passwd is world-


readable.

Passwords are stored as hashes (SHA-512, MD5, etc.), not plain text.
It prevents regular users from reading encrypted passwords and running offline brute-force
attacks.

4 Differentiate between internal and external commands in UNIX with examples.

Feature Internal Commands External Commands

Definition Built into the shell Stored as separate executable programs

Execution Executed within the shell process Loaded from disk into a new process

Speed Faster Slightly slower (disk I/O)

Examples cd , echo , pwd , history , alias ls , date , cal , who , cat

Use the type command to identify command type:

type cd # cd is a shell builtin


type ls # ls is /bin/ls

5 Explain the following UNIX commands ls , who , date , passwd , cal .


with syntax, examples, purpose, and
commonly used options:

1. ls — List Directory Contents

Syntax: ls [options] [directory]

Purpose: Displays files and directories.

ls — list files in current directory

ls -l — long format (permissions, owner, size, date)

ls -a — show hidden files

ls -la — combine both

$ ls -l
-rwxr-xr-- 1 kumar metal 195 May 10 13:45 chap01
-rwxr-xr-x 2 kumar metal 512 May 09 12:55 helpdir

2. who — Show Logged-in Users

Syntax: who [options]

Purpose: Displays information about currently logged-in users.


who — username, terminal, login time

who -u — includes idle time and process ID

who -q — quick count of users

who am i — current user info

$ who
navya pts/0 Mar 10 10:15
user1 pts/1 Mar 10 10:20

3. date — Display/Set System Date

Syntax: date [options] [+format]

Purpose: Shows or sets system date and time.

date — current date/time

date +"%d-%m-%Y" — custom format

date +"%T" — time only

$ date
Wed Mar 11 14:35:10 IST 2026

$ date +"%d-%m-%Y"
11-03-2026

4. passwd — Change User Password

Syntax: passwd [username]

Purpose: Maintains system security by updating passwords.

passwd — change own password

passwd -l username — lock account

passwd -u username — unlock account

passwd -d username — delete password

5. cal — Display Calendar

Syntax: cal [options] [month] [year]

Purpose: Shows calendar in terminal.

cal — current month

cal 3 2026 — March 2026

cal 2026 — entire year


6 Demonstrate type , man , more commands. Explain syntax and illustrate
the usage of and how they help identify command types,
access documentation, and view large
outputs.

type — Identify Command Type

Syntax: type command_name

$ type ls
ls is /bin/ls # external command
$ type cd
cd is a shell builtin # internal command
$ type echo
echo is a shell builtin

man — Access Manual Pages

Syntax: man [options] command

Sections in a man page: NAME, SYNOPSIS, DESCRIPTION, OPTIONS, OPERANDS, EXIT


STATUS, SEE ALSO.

man ls — open manual for ls

man -k copy — search by keyword (apropos)

man -f ls — short description (whatis)

man -a passwd — show all pages for command

more — View File Page by Page

Syntax: more [options] filename

Navigation Keys:

Space — next page

Enter — next line

b — back one page

/word — search for "word"

n — next occurrence

q — quit

v — open in vi

Repeat Factor: Type a number before a command to repeat it (e.g., 10Enter moves 10 lines,
5Space moves 5 pages).

Pipeline Usage:

ls -l | more
ps -aux | more

7 What are POSIX and SUS? Explain their purpose in standardizing UNIX OS and
ensuring portability, compatibility, and interoperability.

POSIX (Portable Operating System Interface)

Developed by IEEE.

A set of standards defining how UNIX-like OS should behave.

POSIX.1 — specifies C API and system calls (kernel interface).

POSIX.2 — deals with the shell and utilities.

Ensures compatibility between UNIX systems; allows programs to run on different UNIX-like OS
without modification.

SUS (Single UNIX Specification)

Developed by The Open Group.

Defines what an OS must support to be officially called UNIX.

Provides a single unified UNIX standard and ensures system consistency.

Allows official UNIX certification (e.g., UNIX 03, UNIX V7).

Feature POSIX SUS

Developed by IEEE The Open Group

Focus API standards Full UNIX certification

Purpose Ensures portability Ensures official UNIX branding

Relationship Forms part of SUS Includes POSIX + additional specs

8 Explain echo and printf commands in UNIX. Discuss syntax, options, and
the examples.

echo Command

Syntax: echo [options] [string]

Used to display text or messages on the terminal.

$ echo Hello
Hello
$ echo Hello World
Hello World
$ name="Navya"; echo $name
Navya
$ echo -e "UNIX
Shell" # -e enables escape sequences
UNIX
Shell

printf Command

Syntax: printf "format string" [arguments]

Used for formatted output (similar to C printf ).

Specifier Meaning

%s String

%d Decimal integer

%f Floating point

%o Octal

%x Hexadecimal

$ printf "Hello World


"
Hello World
$ printf "Name: %s Age: %d
" "Navya" 21
Name: Navya Age: 21
$ printf "Value: %.2f
" 3.14159
Value: 3.14

Common Escape Sequences

— New line

— Horizontal tab

— Audible bell

\ — Backslash

9 What is UNIX? Explain its brief history and how UNIX influenced modern operating
systems.

What is UNIX?
UNIX is a multiuser, multitasking operating system developed in the late 1960s. It provides a
stable, secure, and efficient environment for servers, workstations, and embedded systems.

Brief History

1969–1970s — Birth of UNIX at Bell Labs by Ken Thompson and Dennis Ritchie.

1971 — Thompson Shell (first UNIX shell).

1977 — Bourne Shell ( sh ) by Stephen Bourne.

Late 1970s — C Shell ( csh ) by Bill Joy.

1980s — Korn Shell ( ksh ) by David Korn.

1989 — Bash (Bourne Again Shell) by Brian Fox for GNU Project.

Influence on Modern Operating Systems

Linux is a UNIX-like OS and follows POSIX standards.

macOS is certified UNIX (SUS).

Android uses a Linux kernel (UNIX-like).

Concepts like hierarchical file systems, pipes, shell scripting, and process management
originated in UNIX.

10 What man command? Explain its purpose, usage, and how to access command
is the manuals and options with examples.

The man command displays the manual (help documentation) for commands, programs, and
system calls.

Syntax: man [options] <command>

Sections in a Man Page

1. NAME — command name and short description

2. SYNOPSIS — syntax

3. DESCRIPTION — detailed explanation

4. OPTIONS — available flags

5. OPERANDS / EXIT STATUS / SEE ALSO

Common Options

Option Description Example

-a Display all available pages man -a passwd

-f Short description (whatis) man -f ls


-k Search by keyword (apropos) man -k copy

-w Location of man page file man -w ls

-P Use specific pager man -P more ls

Related Commands

apropos keyword — list commands related to keyword

whatis command — one-line description

11 Explain the usage of file more in UNIX. Discuss options, navigation keys,
viewing command repeat factor, and search patterns.

Syntax: more [options] filename

Purpose: View text files one screen at a time.

Common Options

-d — display helpful prompts

-f — count logical lines

-p — clear screen before displaying page

-s — squeeze multiple blank lines

-c — replace screen instead of scrolling

Navigation Keys

Key Function

Space Next page

Enter Next line

b Back one page

/word Search for "word"

n Next occurrence

q Quit

v Open in vi

Repeat Factor

Type a number before a command to repeat it:


10Enter — move down 10 lines

5Space — move forward 5 pages

3b — move back 3 pages

4/error — find 4th occurrence of "error"

Pipeline Usage

ls -l | more
ps -aux | more
cat [Link] | more

12 Explain how to create a user environment in UNIX. Describe steps: adding a new
user, setting password, creating home directory, assigning shell, and configuring
environment variables.

Steps to Create a User Environment

1. Add New User

sudo useradd -m -s /bin/bash -c "Navya" navya

2. Set Password

sudo passwd navya

3. Create Home Directory (usually auto-created with -m ; if not:)

sudo mkdir /home/navya


sudo chown navya:navya /home/navya
sudo chmod 700 /home/navya

4. Assign Default Shell

sudo usermod -s /bin/bash navya

5. Configure Environment Files

Edit ~/.bashrc , ~/.bash_profile , or ~/.profile :

export PATH=$PATH:/home/navya/bin
export EDITOR=vi

6. Set User Group


sudo usermod -aG developers navya

7. Verify

su - navya
whoami
pwd

13 Explain commands to add, modify, and delete users in UNIX along with syntax,
options, and examples.

useradd — Add User

sudo useradd [options] username

Option Description

-m Create home directory

-d /path Custom home directory

-s /bin/bash Specify shell

-c "comment" GECOS info

-u UID Specify user ID

-g group Primary group

sudo useradd -m -s /bin/bash -c "Alice" alice


sudo passwd alice

usermod — Modify User

sudo usermod [options] username

Option Description

-l newname Change username

-d /new/home -m Change home & move files


-s /new/shell Change shell

-c "new comment" Update GECOS

-aG groups Add to supplementary groups

sudo usermod -l alicia alice


sudo usermod -s /bin/zsh alicia
sudo usermod -aG developers,admins alicia

userdel — Delete User

sudo userdel [options] username

Option Description

-r Remove home directory and mail spool

-f Force removal

sudo userdel alice # keep home


sudo userdel -r alice # remove home

Module 2 FILE SYSTEM

1 Explain file system organization in UNIX.

UNIX uses a hierarchical (tree) file system with a single root directory / .

Key Directories

/ — Root directory (top level)

/bin — Essential user binaries (commands)

/sbin — System binaries

/usr — User programs, libraries, docs ( /usr/bin , /usr/lib )

/home — User home directories

/etc — Configuration files

/dev — Device files


/tmp — Temporary files

/var — Variable data (logs, spool)

/lib — Shared libraries

/proc — Process information

/mnt / /media — Mount points

Parent-Child Relationship

Every directory (except root) has exactly one parent. A parent can have multiple children. Special
symbols: . (current directory) and .. (parent directory).

2 Discuss file permissions and directory permissions in detail.

File Permissions

Three types of users:

Owner (u) — creator of the file

Group (g) — group associated with the file


Others (o) — all other users

Three permission types:

Symbol Permission Numeric

r Read 4

w Write 2

x Execute 1

Directory Permissions

Read (r) — list contents (use ls )

Write (w) — create, delete, rename files inside

Execute (x) — enter directory (use cd ) and access files if names are known

Note: A directory with r but no x lets you list names but not open files. A directory with x
but no r lets you access files if you know their names but not list them.

3 Explain directory commands: cd , pwd , mkdir , rmdir .

pwd — Print Working Directory


$ pwd
/home/navya/Documents

cd — Change Directory

cd /home/navya/Documents # absolute path


cd Documents # relative path
cd # go to home directory
cd ~ # go to home directory
cd .. # parent directory
cd - # previous directory
cd / # root directory

mkdir — Make Directory

mkdir Projects # single directory


mkdir dir1 dir2 dir3 # multiple directories
mkdir -p a/b/c # create parent directories if needed

rmdir — Remove Directory

rmdir Projects # remove empty directory


rmdir dir1 dir2 # multiple empty directories

rmdir only removes empty directories. To remove non-empty directories, use rm -r


directory_name .

4 Explain file commands: cat , mv , rm , cp , wc .

cat — Concatenate/Display Files

cat [Link] # display content


cat > [Link] # create new file (overwrite)
cat >> [Link] # append to file
cat file1 file2 > file3 # combine files

cp — Copy

cp [Link] [Link] # copy file


cp file1 file2 /home/user/ # copy to directory
cp -r Folder1 /home/user/ # copy directory recursively
cp -i [Link] [Link] # prompt before overwrite
mv — Move/Rename

mv [Link] [Link] # rename


mv [Link] /home/user/ # move to directory

rm — Remove

rm [Link] # delete file


rm [Link] [Link] # delete multiple
rm -r FolderName # delete directory recursively
rm -f [Link] # force delete
rm -i [Link] # interactive (ask confirmation)

wc — Word Count

wc [Link] # lines, words, characters


wc -l [Link] # lines only
wc -w [Link] # words only
wc -c [Link] # characters only

Output format: lines words bytes filename

5 Explain file permissions and representation.

Permissions are represented in two ways:

1. Symbolic (Text) Representation

Format: drwxr-xr-x

1st char: d (directory), - (file), l (link)

Next 3: Owner permissions ( rwx )

Next 3: Group permissions ( r-x )


Last 3: Others permissions ( r-x )

2. Numeric (Octal) Representation

Permission Value

r (read) 4

w (write) 2

x (execute) 1

Examples:
7 = 4+2+1 = rwx

6 = 4+2 = rw-

5 = 4+1 = r-x

4 = r--

0 = ---

Common modes:

755 = rwxr-xr-x (owner full, others read+execute)

644 = rw-r--r-- (owner read+write, others read-only)

777 = rwxrwxrwx (full access to all)

6 Explain the basic file attributes in UNIX with suitable examples.

Attribute Description

File Name Name stored in directory

File Type Regular, directory, symbolic link, device, etc.

Permissions rwx for owner, group, others

Owner User who owns the file

Group Group associated with the file

Size File size in bytes

Timestamps Creation, last modification, last access

Link Count Number of hard links

Inode Number Unique identifier for the file metadata

View with:

ls -l [Link]
ls -li [Link] # includes inode number

7 Demonstrate the usage of chown and chgrp commands with examples.

chown — Change Owner


Only root can change file ownership.

$ ls -l note
-rwxr----x 1 kumar metal 347 May 10 20:30 note

$ sudo chown sharma note


$ ls -l note
-rwxr----x 1 sharma metal 347 May 10 20:30 note

Change owner and group together:

sudo chown user:group [Link]

chgrp — Change Group

A normal user can change the group if they own the file and belong to the target group.

$ ls -l [Link]
-rw-r--r-- 1 kumar metal 139 Jun 8 16:43 [Link]

$ chgrp dba [Link]


$ ls -l [Link]
-rw-r--r-- 1 kumar dba 139 Jun 8 16:43 [Link]

8 Explain relative and absolute permission methods.

Relative (Symbolic) Method — chmod

Modifies existing permissions by adding, removing, or setting.

Syntax: chmod [who][operator][permission] filename

Who: u (owner), g (group), o (others), a (all)

Operator: + (add), - (remove), = (set exactly)


Permission: r , w , x

chmod u+x [Link] # add execute for owner


chmod g-w [Link] # remove write from group
chmod o=r [Link] # set others to read-only
chmod a+r [Link] # add read for everyone

Absolute (Numeric) Method — chmod

Sets exact permissions using octal numbers (0-7) for each class.

chmod 755 [Link] # rwxr-xr-x


chmod 644 [Link] # rw-r--r--
chmod 777 [Link] # rwxrwxrwx
chmod 000 [Link] # ----------

9 Define a file in UNIX. Explain different types of files, naming conventions, and
directory structure organization.

Definition of a File

A file is a container for storing information. In UNIX, everything is a file — data, directories,
devices, and processes are all represented as files. File attributes (type, permissions, owner, size)
are stored in an inode, not with the filename.

Types of Files

Type Symbol Description Example

Ordinary/Regular - Contains data (text or binary) [Link] , program.c

Directory d Contains files and subdirectories /home , /etc

Device File b or c Represents hardware devices /dev/sda , /dev/tty

Symbolic Link l Pointer to another file link1 -> file1

File Naming Conventions

Max length: 255 characters

Case-sensitive: [Link] ≠ [Link]

Allowed: letters, numbers, _ , - , .


Files starting with . are hidden (e.g., .bashrc , .profile )

UNIX does not require file extensions (used for user convenience)

Directory Structure Organization

Hierarchical tree starting at root / . Each directory can contain files and subdirectories. Path
names:

Absolute path: starts from / (e.g., /home/user/[Link] )

Relative path: starts from current directory (e.g., [Link] , ../docs )

10 Explain file attributes in UNIX. How are they ls output and explain each field
displayed using commands? Illustrate -l for files and directories.

Displaying Attributes
ls -l [Link] # file attributes
ls -ld directory/ # directory attributes (not contents)
ls -li # include inode numbers

ls -l Output Format

-rw-r--r-- 1 navya staff 1024 Apr 6 10:00 [Link]

Field Value Meaning

1 - File type ( - =file, d =directory, l =link)

2-4 rw- Owner permissions

5-7 r-- Group permissions

8-10 r-- Others permissions

11 1 Link count

12 navya Owner name

13 staff Group name

14 1024 Size in bytes

15-17 Apr 6 10:00 Last modification date & time

18 [Link] File name

Directory Example (ls -ld)

drwxr-xr-x 2 navya staff 4096 Apr 6 10:00 Documents

d — directory

2 — links (includes . and .. )

4096 — directory size (typically 4KB block size)

Module 3 EDITORS, RE & REDIRECTION


1 Illustrate the standard editor in UNIX. Explain the different modes of vi editor in
detail. Describe all commands used in each mode with examples.

vi Editor — The Standard UNIX Editor

vi stands for "visual editor." It is available on almost all UNIX/Linux systems, uses minimal
resources, and works entirely via keyboard (no mouse required). It is the de facto standard editor
because of its ubiquity and consistency across platforms.

Three Modes of vi

Mode Purpose How to Enter How to Exit

Navigation, editing, Press i , a ,


Command Mode Default on open
deleting, copying o , or :

Press i , a , I ,
Insert (Input) Mode Typing and inserting text Press Esc
A , o , O

Ex Mode (Last Line / Saving, quitting, Press Enter or


Press :
Execute Mode) searching, substituting Esc

Command Mode Commands

Command Function

h , j , k , l Move left, down, up, right

w , b , e Next word, previous word, end of word

0 , ^ , $ Start of line, first non-blank, end of line

gg , G , nG Go to first line, last line, line n

Ctrl+f , Ctrl+b Forward/backward one page

x , dd , 4dd Delete character, delete line, delete 4 lines

yy , 3yy Copy (yank) line, copy 3 lines

p , P Paste after/before cursor (or below/above line)

u , Ctrl+r Undo, redo

/pattern , ?pattern Search forward/backward

n , N Next/previous occurrence

Insert Mode Commands


Command Function

i Insert before cursor

a Append after cursor

I Insert at beginning of line

A Append at end of line

o Open new line below

O Open new line above

r Replace single character

R Replace continuously (overwrite mode)

s Substitute character(s)

S Substitute entire line

Ex Mode Commands

Command Function

:w Save (write)

:q Quit

:wq or :x Save and quit

:q! Quit without saving

:w filename Save as new file

:w! filename Force overwrite

:sh Escape to UNIX shell

:recover Recover from crash

:set number Show line numbers

:set ic Ignore case in search

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

Repeat Factor
Type a number before a command to repeat it: 5j (move down 5 lines), 4dd (delete 4 lines),
2yy (copy 2 lines).

Invoking and Quitting vi

vi filename # open file


vi +10 filename # open at line 10
vi + filename # open at last line
vi -R filename # read-only mode
vi file1 file2 # open multiple files

ZZ # save and quit (command mode)


:wq # save and quit
:q! # quit without saving

2 Discuss regular expressions with examples using grep and egrep .

Regular Expressions (RE)

A regular expression is a pattern used to match text. It is used in commands like grep , sed ,
awk , and vi .

Basic Regular Expressions (BRE) — grep

Symbol Meaning Example

. Any single character grep "c.t" file → cat, cut

* Zero or more occurrences grep "a*b" file → b, ab, aaab

^ Start of line grep "^Hello" file

$ End of line grep "world$" file

\{n\} Exactly n times grep "a\{3\}" file → aaa

\{n,m\} Between n and m times grep "a\{2,4\}" file

\| OR (escaped) grep "cat\|dog" file

\( \) Grouping (escaped) grep "\(ab\)*" file

Extended Regular Expressions (ERE) — egrep / grep -E

Symbol Meaning Example


+ One or more egrep "a+b" file → ab, aab

? Zero or one egrep "colou?r" file → color, colour

{n} Exactly n times egrep "a{3}" file

| OR (no escape needed) egrep "cat|dog" file

( ) Grouping (no escape) egrep "(ab)+" file

grep Options

Option Description

-i Ignore case

-v Invert match (show non-matching lines)

-n Show line numbers

-c Count matching lines

-l Show only filenames

-E Use extended regex (same as egrep)

Examples

grep "MH" [Link] # search for "MH"


grep -i "mh" [Link] # case-insensitive
grep -v "MH" [Link] # exclude "MH"
grep -n "MH" [Link] # with line numbers
grep -c "MH" [Link] # count matches
grep -l "MH" *.lst # files containing pattern
egrep "MH|VV" [Link] # OR condition
egrep "a{3}" [Link] # exactly 3 a's

3 Classify set , map , abbr commands in the vi editor with syntax and
the and examples.

set Command — Change vi Settings

Used to customize the vi editor environment.

Command Function
:set number / :set nu Show line numbers

:set nonumber Hide line numbers

:set ic Ignore case in search

:set ai Auto indentation

:set noai Disable auto indentation

:set showmode Display current mode

:set ro Read-only mode

:set list Show special characters

map Command — Create Keyboard Shortcuts

Assigns a key to perform one or more commands.

Syntax: :map key sequence

:map Q :q! # Press Q to quit without saving


:map x dd # Press x to delete entire line
:map jj # Press jj instead of Esc
:map A iHello # Press A to insert "Hello"

abbr Command — Create Abbreviations

Creates short forms that automatically expand to full text while typing.

Syntax: :ab short long_text

:ab inc include # typing "inc" becomes "include"


:ab #d #define # typing "#d" becomes "#define"
:ab main int main() # typing "main" expands to full function

.exrc File

These settings can be saved permanently in the ~/.exrc file so they load every time vi starts.

set number
set autoindent
set showmode
ab inc include
map Q :q!
4 Illustrate the shell's interpretive cycle with a neat diagram and suitable explanation.

Shell Interpretive Cycle

The shell acts as an interface between the user and the kernel. It processes commands in a
continuous cycle:

1. Prompt Display — Shell displays a prompt ( $ or # ) indicating readiness.

2. Command Input — User types a command (e.g., ls -l ).

3. Lexical Analysis (Parsing) — Shell breaks input into tokens: command, options, arguments.

4. Syntax Checking — Validates command structure; displays error if invalid.

5. Command Lookup — Determines if command is built-in or external. For external commands,


searches directories in PATH .

6. Execution

Built-in: executed directly by shell.

External: shell creates a new process using fork() and executes using exec() .

7. Wait (if foreground) — Shell waits for command to complete before showing next prompt. For
background processes ( & ), shell does not wait.

8. Output Display — Result is displayed on standard output (terminal).

Flow: Prompt → Read Input → Parse → Check Syntax → Lookup → Execute → Wait →
Display Output → Loop back to Prompt

5 Categorize the three standard files in UNIX. Describe input and output redirection
with examples.

Three Standard Files (Streams)

File Default
Stream Description
Descriptor Source/Destination

Standard Input
0 Keyboard Input to a command
(stdin)

Standard Output Normal output of a


1 Terminal (screen)
(stdout) command

Standard Error
2 Terminal (screen) Error messages
(stderr)

Input Redirection (<)


Takes input from a file instead of keyboard.

sort < [Link] # sort reads from [Link]


cat < [Link] # display file content

Output Redirection (> and >>)

Sends output to a file instead of screen.

ls > [Link] # overwrite


date >> [Link] # append
cat file1 file2 > file3 # combine files

Error Redirection (2>)

ls wrongfile 2> [Link] # redirect error to file


ls file1 wrongfile > [Link] 2>&1 # stdout and stderr to same file
ls file1 wrongfile > [Link] 2> [Link] # separate files

Here Document (<<)

Provides inline input to a command.

cat << END


Hello
Welcome to UNIX
END

6 Distinguish basic and extended regular expressions with examples.

Feature Basic RE (BRE) — grep Extended RE (ERE) — egrep / grep -E

+ (one or more) Needs escape: \+ Direct use: +

? (zero or one) Needs escape: \? Direct use: ?

{n} (repetition) Needs escape: \{n\} Direct use: {n}

| (OR) Needs escape: \| Direct use: |

( ) (grouping) Needs escape: \( \) Direct use: ( )

Command grep egrep or grep -E

Examples
# BRE
grep "cat\|dog" [Link] # OR (escaped)
grep "a\{3\}" [Link] # exactly 3 a's (escaped)

# ERE
egrep "cat|dog" [Link] # OR (no escape)
egrep "a{3}" [Link] # exactly 3 a's (no escape)
egrep "colou?r" [Link] # optional u (no escape)
egrep "a+b" [Link] # one or more a (no escape)

7 Classify set , map , abbr commands in the vi editor with syntax and
the and examples.

See Question 3 of Module 3 above for complete coverage.

8 Distinguish basic and extended regular expressions with examples.

See Question 6 of Module 3 above for complete coverage.

9 Explain combining commands using pipes and filters.

Pipe (|)

A pipe connects two commands, sending the output of the first command as input to the second.

Syntax: command1 | command2

ls -l | more # list files page by page


ls -l | wc -l # count number of files
ps -aux | grep "bash" # find bash processes
cat [Link] | sort | uniq | wc -l # pipeline of multiple commands

Filters

Filters are commands that read from stdin, process data, and write to stdout.

Filter Purpose

cat Concatenate/display

grep Search patterns

sort Sort lines


wc Count lines/words/characters

head First n lines

tail Last n lines

cut Extract columns

paste Merge lines

tr Translate characters

tee Split output (display + save)

uniq Remove duplicate lines

tee Command

Sends output to both screen and file simultaneously.

ls | tee [Link] # display and save


ls | tee -a [Link] # append to file

10 Illustrate the concept of filename generation * , ? , and [] with


in UNIX using wildcards. Demonstrate the use character examples.
of classes

Filename Generation (Globbing)

The shell expands wildcard patterns to matching filenames before executing the command.

1. Asterisk (*) — Matches zero or more characters

ls *.txt # all .txt files


ls file* # file, file1, file_data.txt
rm *.log # delete all .log files
cp * /backup/ # copy all files to backup

2. Question Mark (?) — Matches exactly one character

ls file?.txt # [Link], [Link] (NOT [Link])


ls ?.c # a.c, b.c (single char before .c)
rm temp?.bak # [Link], [Link]

3. Character Classes [ ] — Matches one character from the set


ls file[1-3].txt # [Link], [Link], [Link]
ls file[abc].txt # [Link], [Link], [Link]
ls [A-Z]* # files starting with uppercase letter
ls file[!1-3].txt # any file except file1, file2, file3

Escaping Wildcards

To use wildcards as literal characters:

ls \*.txt # look for file literally named *.txt


echo '*.txt' # single quotes prevent expansion
echo "*.txt" # double quotes prevent expansion

Module 4 SHELL PROGRAMMING

1 Explain with examples: a) Ordinary read and readonly commands, d)


and environment variables, b) The Command line
.profile file, c) arguments in shell
scripts.

a) Ordinary and Environment Variables

Feature Ordinary Variable Environment Variable

Scope Local to current shell Available to child shells/processes

Creation var=value export var=value

Inheritance Not inherited Inherited by child processes

Use Temporary/local use System-wide or session-wide

# Ordinary variable
name="Navya"
echo $name # Output: Navya

# Environment variable
export city="Bengaluru"
echo $city # Output: Bengaluru
bash # start child shell
echo $city # still available: Bengaluru
exit # return to parent

b) The .profile File

.profile is a startup file located in the user's home directory. The shell automatically executes it
when the user logs in.

Common Uses:

Setting PATH

Setting terminal type

Displaying welcome messages


Defining aliases and variables

#.profile example
PATH=/bin:/usr/bin:/home/user/bin
export PATH
echo "Welcome to UNIX"
export EDITOR=vi

Apply changes without logging out:

source ~/.profile
. ~/.profile

c) read and readonly Commands

read — Accepts input from keyboard and stores in a variable.

#!/bin/sh
echo "Enter your name:"
read name
echo "Welcome $name"

# Output:
# Enter your name: Navya
# Welcome Navya

readonly — Makes a variable constant (cannot be modified).

city="Delhi"
readonly city
city="Mumbai" # Error: city: is read only

pi=3.14
readonly pi # constant throughout script
d) Command Line Arguments

Values passed to a script during execution, stored in positional parameters.

Parameter Meaning

$0 Script name

$1 , $2 , $3 ... 1st, 2nd, 3rd argument

$# Total number of arguments

$* All arguments as single string

$@ All arguments as separate strings

$$ Process ID of current shell

#!/bin/sh
echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "Total Arguments: $#"
echo "All Arguments: $*"

# Execution:
# ./[Link] Sneha Mumbai
# Output:
# Script Name: ./[Link]
# First Argument: Sneha
# Second Argument: Mumbai
# Total Arguments: 2
# All Arguments: Sneha Mumbai

2 Explain exit and exit status of a command. && , || ) for conditional


the use Discuss logical operators ( execution with
of examples.

exit Command

Terminates the current shell or shell script. Can optionally return a status code.

Syntax: exit [status]

#!/bin/sh
echo "Start of Script"
exit
echo "End of Script" # This line never executes
# Output: Start of Script

Exit Status

Every command returns an exit status after execution:

Exit Status Meaning

0 Success (true)

Non-zero Error or failure (false)

The special variable $? stores the exit status of the last command.

ls
echo $? # Output: 0 (success)

ls wrongfile
echo $? # Output: 2 (failure)

Logical AND (&&)

Second command executes only if the first succeeds (exit status 0).

mkdir test && cd test # cd runs only if mkdir succeeds

Logical OR (||)

Second command executes only if the first fails (non-zero exit status).

ls [Link] || echo "File not found"


# If [Link] doesn't exist, prints "File not found"

Logical NOT (!)

Reverses the result of a command.

! ls wrongfile # returns success (0) because ls fails

Combining Operators

mkdir project && cd project || echo "Operation failed"


# If mkdir succeeds, cd runs. If either fails, echo runs.
3 Describe the test command and its shortcut forms with examples.

The test command checks conditions in shell scripts. Returns 0 (true) if condition is satisfied,
non-zero (false) otherwise.

Syntax

test condition
# OR shortcut form:
[ condition ]

Important: Spaces are mandatory inside [ ] : [$a -eq 10] is WRONG. Correct: [ $a -
eq 10 ]

Numeric Operators

Operator Meaning Example

-eq Equal to [ $a -eq $b ]

-ne Not equal to [ $a -ne $b ]

-gt Greater than [ $a -gt $b ]

-lt Less than [ $a -lt $b ]

-ge Greater than or equal [ $a -ge $b ]

-le Less than or equal [ $a -le $b ]

String Operators

Operator Meaning Example

= Strings are equal [ "$a" = "$b" ]

!= Strings are not equal [ "$a" != "$b" ]

-z String length is zero [ -z "$a" ]

-n String length is not zero [ -n "$a" ]

File Test Operators

Operator Meaning Example


-f File exists [ -f [Link] ]

-d Directory exists [ -d mydir ]

-r File has read permission [ -r [Link] ]

-w File has write permission [ -w [Link] ]

-x File has execute permission [ -x [Link] ]

Examples

a=10
[ $a -eq 10 ]
echo $? # Output: 0 (true)

[ $a -gt 5 ] && echo "a is greater than 5" # Output: a is greater than 5

[ -f [Link] ] && echo "File exists" || echo "File not found"

name="unix"
[ "$name" = "unix" ]
echo $? # Output: 0 (true)

4 Illustrate the use of conditional if , while , for , case with


control statements: and examples.

1. if Statement

Used for decision making based on conditions.

#!/bin/sh
a=10
if [ $a -gt 5 ]
then
echo "a is greater than 5"
fi

# if-else
if [ -f [Link] ]
then
echo "File exists"
else
echo "File not found"
fi

# if-elif-else
if [ $a -gt 10 ]
then
echo "Greater than 10"
elif [ $a -eq 10 ]
then
echo "Equal to 10"
else
echo "Less than 10"
fi

2. while Loop

Repeats commands while condition is true.

#!/bin/sh
i=1
while [ $i -le 5 ]
do
echo $i
i=`expr $i + 1`
done

# Output:
# 1
# 2
# 3
# 4
# 5

3. for Loop

Repeats for a fixed set of values.

#!/bin/sh
for i in 1 2 3 4 5
do
echo $i
done

# OR using range-like behavior


for file in *.txt
do
echo "Processing: $file"
done

4. case Statement

Multiple choice decision making.

#!/bin/sh
echo "Enter a number:"
read n
case $n in
1) echo "One" ;;
2) echo "Two" ;;
3) echo "Three" ;;
*) echo "Invalid" ;;
esac

# Output (if input is 2):


# Two

5 Describe test command and its if , while , for , case with


the shortcut forms. and examples.
Illustrate the use of
conditional control
statements:

See Questions 3 and 4 of Module 4 above for complete coverage.

6 Explain the concept of << ) and trap command with examples. Write a simple
here document ( the shell program illustrating them.

Here Document (<<)

Provides multiple lines of inline input to a command within a script.

Syntax:

command << delimiter


text
text
delimiter

Examples

# Example 1: Display text


cat << END
Hello
Welcome to UNIX
END
# Output:
# Hello
# Welcome to UNIX

# Example 2: Write to file


cat > [Link] << STOP
This is line 1
This is line 2
STOP
# [Link] contains both lines

trap Command

Catches signals and executes specified commands when signals occur.

Signal Number Meaning

0 0 Exit from script

SIGHUP 1 Hangup signal

SIGINT 2 Interrupt (Ctrl+C)

SIGKILL 9 Kill signal

SIGTERM 15 Termination signal

Examples

# Example 1: Catch Ctrl+C


trap "echo You pressed Ctrl+C" 2
while true
do
echo "Running..."
sleep 2
done

# Example 2: Display message before exit


trap "echo Script Ended" 0
echo "UNIX Shell Script"
# Output:
# UNIX Shell Script
# Script Ended

# Example 3: Delete temp file on exit


touch [Link]
trap "rm [Link]" 0
echo "Processing..."
# [Link] is automatically deleted when script exits

Complete Shell Program

#!/bin/sh

# trap to cleanup on exit


trap "echo 'Cleaning up...'; rm -f [Link]" 0
# Create temp file
touch [Link]

# Use here document to write data


cat > [Link] << DATA
Line 1: Hello
Line 2: World
Line 3: UNIX
DATA

echo "File contents:"


cat [Link]

echo "Script completed."


# [Link] will be deleted automatically on exit

7 Discuss file structure in UNIX with emphasis on file inodes and inode structure.
Explain hard links and soft links with examples.

File Structure and Inodes

An inode (Index Node) is a data structure that stores metadata about a file. Every file has a
unique inode number.

Information Stored in an Inode

Field Purpose

File type Regular, directory, link, device

Permissions rwx for owner, group, others

Owner User ID File owner

Group ID Group owner

File size Size in bytes

Link count Number of hard links

Access time Last accessed

Modification time Last modified

Change time Last inode change

Data block pointers Addresses of file data blocks


Not stored in inode: filename (stored in directory) and file content (stored in data blocks).

Viewing Inode Numbers

ls -i [Link] # show inode number


ls -li [Link] # show inode + long listing

Hard Links

A hard link is another name for the same file. Both filenames share the same inode number.

Changes through one name affect the other.

Cannot cross file systems.

Cannot link to directories.

$ echo "Hello" > file1


$ ln file1 file2
$ ls -li
12345 -rw-r--r-- 2 user user 6 May 19 file1
12345 -rw-r--r-- 2 user user 6 May 19 file2
# Both have same inode (12345) and link count 2

Soft Links (Symbolic Links)

A soft link is a shortcut that stores the path to the original file. It has a different inode number.

Can cross file systems.


Can link to directories.

Becomes broken if original file is deleted.

$ touch [Link]
$ ln -s [Link] link1
$ ls -li
1452 -rw-r--r-- 1 user user 0 May 17 [Link]
2678 lrwxrwxrwx 1 user user 9 May 17 link1 -> [Link]
# Different inodes: 1452 vs 2678

Feature Hard Link Soft Link

Inode Same as original Different

Cross filesystem No Yes

Link to directory No Yes

If original deleted Data still accessible Link becomes broken

Command ln original link ln -s original link


8 What are filters in head , tail , cut , paste , sort (with different
UNIX? Explain the and options) with
usage of examples.

Filters

Filters are UNIX commands that read input (from stdin or file), process it, and produce output (to
stdout). They are commonly used with pipes ( | ).

head — Display First Lines

head [Link] # first 10 lines (default)


head -n 5 [Link] # first 5 lines
head -c 20 [Link] # first 20 characters

tail — Display Last Lines

tail [Link] # last 10 lines (default)


tail -n 5 [Link] # last 5 lines
tail -f [Link] # follow/monitor file (live updates)
tail +9 [Link] # all lines from line 9 to end

cut — Extract Columns/Fields

cut -c 1-5 [Link] # characters 1 to 5


cut -d ":" -f 2 [Link] # 2nd field using : as delimiter
cut -d "," -f 1,3 [Link] # 1st and 3rd fields

Example file content:

101:Ravi:CS
102:Anil:IS
$ cut -d ":" -f 2 [Link]
Ravi
Anil

paste — Merge Lines of Files

paste [Link] [Link] # merge with tab delimiter


paste -d "," [Link] [Link] # merge with comma delimiter

Example:
# [Link] # [Link]
Amit 101
Rahul 102

$ paste [Link] [Link]


Amit 101
Rahul 102

$ paste -d "," [Link] [Link]


Amit,101
Rahul,102

sort — Sort Lines

Option Description

-r Reverse order

-n Numerical sort

-k Sort by specific field

-u Remove duplicates

-t Specify delimiter

-f Ignore case

-o Output to file

sort [Link] # alphabetical ascending


sort -r [Link] # reverse alphabetical
sort -n [Link] # numerical sort
sort -u [Link] # unique lines only
sort -t ":" -k 1 [Link] # sort by 1st field (colon-delimited)
sort [Link] -o [Link] # save to file

9 Explain umask and default file permissions in /dev/null and /dev/tty .


the UNIX. Also describe the purpose
concept of special files
of

Default File Permissions

Type Default Permission Symbolic


File 666 rw-rw-rw-

Directory 777 rwxrwxrwx

umask (User Mask)

The umask command sets default permission restrictions by subtracting from the system default.

Formula:

File permission = 666 - umask

Directory permission = 777 - umask

Umask File Permission Directory Permission

000 666 (rw-rw-rw-) 777 (rwxrwxrwx)

022 644 (rw-r--r--) 755 (rwxr-xr-x)

027 640 (rw-r-----) 750 (rwxr-x---)

077 600 (rw-------) 700 (rwx------)

$ umask # display current mask


022

$ umask 027 # change umask


$ touch newfile # creates with 640 (rw-r-----)
$ mkdir newdir # creates with 750 (rwxr-x---)

/dev/null — The Null Device

Acts like a black hole: anything written to it is discarded.

ls > /dev/null # suppress normal output


rm [Link] 2> /dev/null # suppress error messages
command > /dev/null 2>&1 # suppress all output

/dev/tty — The Terminal Device

Represents the current terminal. Used for direct terminal I/O.

echo "Hello" > /dev/tty # display directly on terminal


cat > /dev/tty # read input from terminal

Feature /dev/null /dev/tty

Purpose Discards data Communicates with terminal


Output Nothing stored Displays to user

Use Suppress output Terminal interaction

Nickname Null device / black hole Terminal device

10 Discuss filters like sort , cut , paste with examples.

See Question 8 of Module 4 above for complete coverage of sort, cut, and paste with examples.

Module 5 PROCESSES, SCHEDULING & PERL

1 Explain with examples: a) ps command with bg and fg commands.


Meaning of a process and commonly used
parent–child process options, d)
relationship, b) Mechanism of Background
process creation in UNIX, c) processes and the
use of

a) Process and Parent–Child Relationship

A process is a program in execution. It includes the program code, current activity, memory,
registers, and resources. Each process has a unique Process ID (PID).

Parent Process: The process that creates another process using fork() . It has its own PID
and can create multiple children.

Child Process: The newly created process. It gets its own PID, stores the Parent PID (PPID),
and executes independently.

Example: When you run ls , the shell (parent) creates a child process to execute ls .

b) Mechanism of Process Creation

1. fork() — Parent creates a child process. The child gets a copy of parent's memory and
environment.

2. exec() — Child process may execute a new program, replacing its memory image.

3. Process Scheduling — The UNIX scheduler allocates CPU time to parent and child.

4. exit() — Process terminates and returns status to parent.


Parent Process
|
fork()
|
|--------|
| |
Parent Child
|
exec()
|
New Program

c) ps Command — Process Status

Option Description

ps Current shell processes

ps -e All processes in system

ps -f Full format listing

ps -u user Processes for specific user

ps -a All users' processes (except session leaders)

ps -x Processes without controlling terminal

ps -ef All processes in full format

ps aux Detailed info of all running processes

$ ps
PID TTY TIME CMD
2314 pts/0 00:00:00 bash
2450 pts/0 00:00:00 ps

$ ps -f
UID PID PPID C STIME TTY TIME CMD
user 2314 2300 0 10:20 pts/0 00:00:00 bash

$ ps aux | grep "bash"

d) Background Processes, bg and fg

Background Process: Runs independently without occupying the terminal. Created using & .

sleep 30 & # run in background


sh [Link] & # script in background

bg — Resume a stopped process in the background.

sleep 100 # start in foreground


Ctrl+Z # suspend process
[1]+ Stopped sleep 100
bg # resume in background
[1]+ sleep 100 &

fg — Bring a background or stopped process to the foreground.

sleep 100 & # start in background


fg # bring to foreground

bg fg

Runs in background Brings to foreground

Does not occupy terminal Occupies terminal

Used after suspending Used to continue interaction

2 Explain how commands can at command cron command with the structure
be scheduled in UNIX. and the of the crontab file and
Discuss the examples.

at Command — Execute Once at Specified Time

Schedules a command to run once at a future time.

Syntax: at [time]

Press Ctrl+D to save and exit after entering commands.

Format Example

Specific time at 10:30 AM

Midnight at midnight

Noon at noon

Tomorrow at 5 PM tomorrow

Specific date at 6 PM July 20


Relative at now + 1 hour

$ at 5:00 PM
warning: commands will be executed using /bin/sh
at> echo "Hello" > [Link]
at> Ctrl+D
job 1 at Mon Jul 6 17:00:00 2026

$ at now + 2 minutes
at> sh [Link]
at> Ctrl+D

cron Command — Execute Periodically

cron is a background daemon that checks the crontab file and executes scheduled jobs at
regular intervals.

crontab File Structure

* * * * * command_to_execute
| | | | |
| | | | +---- Day of week (0-7, Sunday=0 or 7)
| | | +------ Month (1-12)
| | +-------- Day of month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)

Examples

# Every day at 6:00 AM


0 6 * * * sh [Link]

# Every 5 minutes
*/5 * * * * echo "Hello"

# Every Monday at 8:00 AM


0 8 * * 1 sh weekly_report.sh

# Every 1st of month at midnight


0 0 1 * * sh monthly_cleanup.sh

# Every weekday at 9:00 AM


0 9 * * 1-5 sh daily_task.sh

crontab Commands

crontab -e # edit crontab


crontab -l # list crontab entries
crontab -r # remove crontab

3 What are signals in UNIX? kill , nice , nohup commands with


Explain the use of and examples.

Signals

Signals are software interrupts sent to processes to control execution: stop, continue, terminate, or
notify events.

Signal Name Purpose

1 SIGHUP Hangup signal

2 SIGINT Interrupt (Ctrl+C)

9 SIGKILL Forcefully terminate

15 SIGTERM Request termination (default)

18 SIGCONT Continue stopped process

19 SIGSTOP Stop process execution

kill Command

Sends signals to processes to terminate or control them.

Syntax: kill [signal] PID

kill 1234 # terminate gracefully (SIGTERM=15)


kill -9 1234 # force kill (SIGKILL)
kill -15 1234 # graceful terminate
kill -19 1234 # stop process
kill -18 1234 # continue stopped process
kill -2 1234 # interrupt (Ctrl+C equivalent)

nice Command

Starts a process with a specific priority (nice value). Range: -20 (highest) to +19 (lowest). Default is
0.

nice -n 10 ls # run ls with lower priority


nice -n 15 sh [Link] # run script with reduced priority
nice -n -5 ./urgent # run with higher priority (requires root)

nohup Command
Stands for "No Hang Up." Runs a process even after the user logs out.

nohup sh [Link] & # continues after logout


nohup python [Link] &
# Output is saved to [Link] by default

4 Explain find command with syntax and various options. Illustrate its usage with
the examples for searching files based on different criteria.

find Command

Searches for files and directories recursively based on various criteria.

Syntax: find [path] [options] [expression]

Option Meaning

-name Search by filename (supports wildcards)

-type Search by type: f (file), d (directory), l (link)

-size Search by size: +1M (greater than 1MB), -100k (less than 100KB)

-perm Search by permissions

-mtime Modified time: -7 (last 7 days), +30 (more than 30 days)

-user Search by owner

-group Search by group

-exec Execute command on found files

-delete Delete found files

Examples

# Find file by name


find . -name "[Link]"

# Find all text files


find . -name "*.txt"

# Find directories only


find . -type d

# Find files larger than 1MB


find . -size +1M

# Find files modified in last 7 days


find . -mtime -7

# Find files with specific permissions


find . -perm 644

# Find and delete .tmp files


find . -name "*.tmp" -delete

# Find and execute command


find . -name "*.log" -exec rm {} \;

# Find files owned by user


find /home -user alice

# Find empty files


find . -type f -empty

5 Describe the structure of a Perl script and explain how to execute it. Discuss
variables, operators, and string handling functions in Perl.

Structure of a Perl Script

#!/usr/bin/perl # Shebang line


# This is a comment

$name = "Unix"; # Variable declaration


print "Welcome to $name
"; # Output statement

1. Shebang Line: #!/usr/bin/perl — tells OS to use Perl interpreter.


2. Comments: Start with # , ignored during execution.

3. Variables: Store data values.

4. Statements: End with semicolon ; .

5. Input/Output: print , <STDIN> , file handles.

Executing a Perl Script

# Step 1: Create script


vi [Link]

# Step 2: Write program


#!/usr/bin/perl
print "Welcome to Perl Programming
";

# Step 3: Save and exit (:wq)

# Step 4: Give execute permission


chmod +x [Link]

# Step 5: Execute
./[Link]
# OR
perl [Link]

Variables in Perl

Type Symbol Example

Scalar $ $num = 10;

Array @ @arr = (1, 2, 3);

Hash (Associative Array) % %data = ('a' => 1);

Operators in Perl

Type Operators

Arithmetic + , - , * , / , %

Assignment = , += , -=

Relational == , != , > , < , >= , <=

Logical && , || , !

String . (concatenation), x (repetition)

$a = 10; $b = 5;
print $a + $b; # 15

$str1 = "Hello";
$str2 = "Perl";
print $str1 . " " . $str2; # Hello Perl

String Handling Functions

Function Purpose Example

length() String length length("Perl") → 4


substr() Extract substring substr("UNIX Shell", 5, 5) → Shell

index() Find position index("abc", "b") → 1

uc() Uppercase uc("perl") → PERL

lc() Lowercase lc("UNIX") → unix

chomp() Remove newline chomp($str)

split() Split string to array split(',', $str)

join() Join array to string join('-', @arr)

reverse() Reverse string reverse("Perl") → lreP

6 Explain the following $_ and $. , b) chop() and chomp() functions.


Perl concepts with Range
examples: a) Default operator,
variables c)

a) Default Variables $_ and $.

$_ — The default input and pattern-searching variable. Automatically stores the current line being
processed.

#!/usr/bin/perl
while (<>) {
print $_; # $_ holds current line
}

# Input:
# Hello
# Perl
# Output:
# Hello
# Perl

$. — Stores the current line number of the last file read. Automatically increments for each line.

#!/usr/bin/perl
while (<>) {
print "Line Number $.: $_";
}

# Input:
# UNIX
# Perl
# Shell
# Output:
# Line Number 1: UNIX
# Line Number 2: Perl
# Line Number 3: Shell

b) Range Operator (..)

Generates a range of values from start to end.

@numbers = (1..5);
print "@numbers"; # Output: 1 2 3 4 5

@letters = ('A'..'E');
print "@letters"; # Output: A B C D E

# In loop
foreach $i (1..5) {
print "$i
";
}
# Output: 1 2 3 4 5

c) chop() and chomp() Functions

Feature chop() chomp()

Removes Last character (any) Newline character only ( )

Safety May remove useful data Safer for user input

Use case General character removal Removing newlines from input

# chop()
$str = "Perl!";
chop($str);
print $str; # Output: Perl

# chomp()
$str = "UNIX
";
chomp($str);
print $str; # Output: UNIX

# chomp with user input


$name = ;
chomp($name);
print "Hello, $name"; # No extra newline
7 Discuss lists and arrays in Perl.

Lists in Perl

An ordered collection of scalar values enclosed in parentheses.

(10, 20, 30, 40)


("Red", "Blue", "Green")
(1, "hello", 3.14)

Arrays in Perl

A variable that stores a list. Declared with @ , elements accessed with $ and index.

@colors = ("Red", "Blue", "Green");


print $colors[0]; # Output: Red
print $colors[1]; # Output: Blue

# Array operations
push(@colors, "Yellow"); # add to end
pop(@colors); # remove from end
shift(@colors); # remove from beginning
unshift(@colors, "Orange"); # add to beginning

# Number of elements
$count = scalar(@colors);

8 Explain @_ variable, splice , push() , pop() , split() , join() functions


the and with
usage examples.
of

@_ — Special Array for Subroutine Arguments

Stores all arguments passed to a subroutine.

#!/usr/bin/perl
sub add {
$a = $_[0]; # first argument
$b = $_[1]; # second argument
$sum = $a + $b;
print "Sum = $sum
";
}
add(10, 20); # Output: Sum = 30
sub display {
my ($name) = @_;
print "Hello $name
";
}
display("Navya"); # Output: Hello Navya

splice() — Add/Remove/Replace Array Elements

Syntax: splice(array, offset, length, list)

@arr = (1, 2, 3, 4, 5);


splice(@arr, 2, 2, 8, 9); # at index 2, remove 2 elements, insert 8, 9
print "@arr"; # Output: 1 2 8 9 5

push() — Add to End of Array

@arr = (10, 20);


push(@arr, 30, 40);
print "@arr"; # Output: 10 20 30 40

pop() — Remove from End of Array

@arr = (1, 2, 3, 4);


pop(@arr);
print "@arr"; # Output: 1 2 3

split() — Split String to Array

$str = "Red,Blue,Green";
@colors = split(',', $str);
print "$colors[0]"; # Output: Red

join() — Join Array to String

@arr = ("Unix", "Perl", "Shell");


$str = join('-', @arr);
print $str; # Output: Unix-Perl-Shell

9 Explain open() , close() , die() functions. keys and values functions.


file and Also
handling discuss
associative
in Perl arrays and
using the use of

File Handling in Perl

open() — Open a File

Mode Symbol Meaning

Read < Read from file

Write > Write to file (overwrite)

Append >> Append to file

# Reading a file
open(FILE, "<", "[Link]") or die "Cannot open file";
while () {
print $_;
}
close(FILE);

# Writing to a file
open(OUT, ">", "[Link]") or die "Cannot write";
print OUT "Hello World
";
close(OUT);

close() — Close a File

close(FILEHANDLE);

die() — Error Handling

Displays error message and terminates the program immediately.

open(FILE, "<", "[Link]") or die "Cannot open file: $!";


# If file doesn't exist, prints error and exits

Associative Arrays (Hashes)

Store data as key-value pairs. Declared with % .

%student = (
"Name" => "Alice",
"Age" => 20,
"Course" => "BCA"
);
print $student{"Name"}; # Output: Alice

keys() Function

Returns all keys from a hash.

%emp = (101 => "John", 102 => "David", 103 => "Sam");
@k = keys(%emp);
print "@k"; # Output: 101 102 103

values() Function

Returns all values from a hash.

@v = values(%emp);
print "@v"; # Output: John David Sam

10 Explain decision-making and loop control structures in Perl with foreach .


emphasis on

Decision-Making Structures

# if statement
$num = 10;
if ($num > 5) {
print "Greater than 5
";
}

# if-else
if ($num > 15) {
print "Greater than 15
";
} else {
print "Not greater than 15
";
}

# if-elsif-else
if ($num > 15) {
print "Greater than 15
";
} elsif ($num > 5) {
print "Greater than 5
";
} else {
print "5 or less
";
}

Loop Control Structures

# for loop
for ($i = 0; $i < 5; $i++) {
print "$i
";
}

# while loop
$i = 0;
while ($i < 5) {
print "$i
";
$i++;
}

# do-while loop
$i = 0;
do {
print "$i
";
$i++;
} while ($i < 5);

foreach Loop (Emphasis)

The foreach loop iterates through elements of a list or array. It is the most commonly used loop
for array processing.

# Using list
foreach $num (1, 2, 3, 4, 5) {
print "$num
";
}

# Using array
@colors = ("Red", "Green", "Blue");
foreach $color (@colors) {
print "$color
";
}

# Using range
foreach $i (1..10) {
print "$i ";
}
# Output: 1 2 3 4 5 6 7 8 9 10
# Using $_ (default variable)
foreach (1..5) {
print "$_
"; # $_ holds current element
}

11 Discuss regular expressions in Perl, including simple and multiple search patterns.
Explain match and substitute operators with examples. Also describe how
subroutines are defined and used.

Regular Expressions in Perl

Patterns used for searching, matching, and manipulating text.

Syntax: $string =~ /pattern/

Simple Search Pattern

$str = "Welcome to Perl Programming";


if ($str =~ /Perl/) {
print "Pattern Found
";
}
# Output: Pattern Found

$str = "UNIX";
if ($str =~ /N/) {
print "Character Found
";
}
# Output: Character Found

Multiple Search Patterns

Use | (OR) to search for multiple patterns.

$str = "I like Perl";


if ($str =~ /Perl|Python/) {
print "Match Found
";
}
# Output: Match Found

# Common regex metacharacters


# . -> any single character
# * -> zero or more
# + -> one or more
# ? -> zero or one
# ^ -> start of string
# $ -> end of string

$str = "cat";
if ($str =~ /c.t/) {
print "Matched
"; # matches cat, cut, cot
}

Match Operator (m//)

$text = "Welcome to Perl";


if ($text =~ /Perl/) {
print "Pattern Found
";
}

# Case-insensitive match
$text = "PERL Programming";
if ($text =~ /perl/i) {
print "Match Found
";
}

# Global match
$text = "cat dog cat rat";
while ($text =~ /cat/g) {
print "cat found
";
}
# Output: cat found (twice)

Substitute Operator (s///)

# Replace first occurrence


$text = "Perl is easy. Perl is powerful.";
$text =~ s/Perl/Python/;
print "$text
";
# Output: Python is easy. Perl is powerful.

# Replace all occurrences (g flag)


$text = "Perl is easy. Perl is powerful.";
$text =~ s/Perl/Python/g;
print "$text
";
# Output: Python is easy. Python is powerful.

# Case-insensitive substitution (ig flags)


$text = "PERL perl Perl";
$text =~ s/perl/Python/ig;
print "$text
";
# Output: Python Python Python

Subroutines in Perl

A block of reusable code defined with sub keyword.

# Defining a subroutine
sub greet {
print "Welcome to Perl Programming
";
}
greet(); # Calling the subroutine

# With parameters
sub display {
my ($name) = @_;
print "Hello $name
";
}
display("Navya"); # Output: Hello Navya

# With multiple parameters


sub add {
my ($a, $b) = @_;
$sum = $a + $b;
print "Sum = $sum
";
}
add(10, 20); # Output: Sum = 30

# Returning values
sub multiply {
my ($x, $y) = @_;
return $x * $y;
}
$result = multiply(5, 4);
print "Result = $result
";
# Output: Result = 20

UNIX Shell Programming — Complete Question Bank Solutions (22CB461)

Dayananda Sagar College of Engineering | Department of Computer Science and Engineering


Semester IV | Modules 1–5

You might also like