1
UNIX PROGRAMMING
I. 1 Mark Questions (Fill in the Blanks / Objective)
From 2024 Paper
1. In ______ language UNIX is written.
2. ______ part of the UNIX operating system interacts with
the hardware.
3. When we log in, the UNIX places us in a directory, called
______ directory.
4. The most common file type is ______ file.
5. ______ command mode is the default mode of vi editor.
6. ______ shell is the most common and best to use.
7. ______ and ______ keywords are used in the while loop.
8. If there are special characters in a pattern, then we've to
enclose them in ______.
From 2023 Paper
9. UNIX was developed by ________.
10. The process of loading the Operating System into
main memory is called ________.
11. When a new process is created, this is called as
________.
12. In UNIX Operating System, 'Vi' is an ________.
13. At the core of the UNIX Operating System ________
exist that process request of shell.
14. The command 'grep' stands for ________.
15. The 'tr' command is used for ________.
16. Two files can be merged based on a key using
________ command.
2
II. 1.5 Mark Questions (Short Answer)
From 2024 Paper
17. What is a kernel?
18. What is the default login shell? How to change it?
19. What is the fork() system call?
20. Which command is used to find all information of the
user?
21. Which four fundamental components of every file
system?
22. What is the lifespan of a shell variable?
23. What is a system call?
24. Write the syntax of the switch statement.
25. Name some utility programs in Unix.
26. What is the purpose of the "grep" utility?
From 2023 Paper
27. What ls command does? Write the syntax of ls
command with all applicable arguments.
28. If a command has the .txt extension, can it be
executed?
29. How can you define PATH?
30. How do you find out the version number of your UNIX
Operating System?
31. Is an option also an argument? How do an argument
differ from an option?
32. State the syntax man command.
33. Write the purpose of pwd, echo and date command.
34. What is the significance of shell in UNIX? State any
three shell names.
3
35. State the three modes of operation used in 'Vi'.
36. What is the essence of chmod command?
III. 2 Mark Questions
From 2024 Paper
37. Differentiate between external and internal
commands in Unix.
38. What are system processes? Give an example.
39. Why might you need to create partitions in Unix?
40. Describe the login process in Unix.
41. What are hard links and symbolic links in Unix?
42. Differentiate between $@ and $*.
43. Tell us about the disadvantages of shell scripting.
44. What is the main difference between BASH and DOS?
45. How does pattern matching work in Unix? Explain.
46. What are functions and how are they defined and
used?
From 2023 Paper
47. Compare the command /* and f*.
48. What the command mv does? Write the syntax of it.
49. If mkdir foo command doesn't create foo directory,
what could be the possible reason?
50. State the two reasons for not having a file name
beginning with a hyphen.
51. What is Shell script? State the essence of Shell
scripting in UNIX.
52. What is the essence of umask command?
4
53. Compare the command echo "$SHELL" with echo
'$SHELL' in UNIX.
54. What happens when you use the command cat file1 >
file2.
55. What is the difference between directory='pwd' and
``directory=`pwd```?
56. Write the syntax of grep command with all its options.
IV. 6 Mark Questions (Long Answer)
From 2024 Paper
57. Explain the architecture of the Unix system.
58. Describe the key features of Unix operating systems.
59. What is the user and group in Unix? Explain related
commands.
60. List and explain common user management commands in
Unix.
61. Explain the different modes of operations used in vi editor.
62. What is a Shell? What are the different types? Explain how
commands are processed.
63. Write a shell script to receive student name, register
number, and marks, then calculate grade.
64. Write the command for grep operations (floating point,
uppercase, etc.).
From 2023 Paper
5
65. What is process? Explain, how shell plays a vital role in
process creation? State the different phases of process
creation.
66. Explain at least 3 commands from each category of
commands that are recognized by shell with their syntax and
example.
67. How do you copy all directories and files from current
directory to its parent directory?
68. State and explain three ways to know your home
directory.
69. Write the command for operations (match filenames,
count users, remove files).
70. Write a shell script accept one or more file names as
argument and convert them into uppercase.
71. Write command to search a pattern with grep, sed and
awk. Test the return value of each command when it fails.
72. Write a shell script that accept a pattern and filenames as
arguments and then counts the number of occurrences of
the pattern in the file.
73. What is Unix OS? Explain the Features of Unix OS.
74. Define Architecture of Unix OS.
75. Define Files & Different Types of Files.
76. Explain Creating File, Copying a File, Renaming a File &
Deleting a File with Syntax & Example.
6
77. What is Unix File System? Explain different blocks of Unix.
78. State & Explain Hard Link & Symbolic Link.
79. Define types of users in Unix.
80. State & Explain concepts of Shell in Unix.
81. What is VI editor in Unix? Explain Command Mode.
82. State & Explain Shell Variable in Unix? Explain it briefly.
83. Define Save & Quit Option in VI Editor.
84. Define Different Delete Options in VI Editor.
85. What is grep command? Explain with Syntax and Options.
86. What is Function in Shell?
87. Explain Loop Concepts in Shell (While, For, Until).
88. Explain If-Else & Case Statements.
7
Answers: 2024 Paper
1. In C language UNIX is written.
2. Kernel part of the UNIX operating system interacts with the
hardware.
3. When we log in, the UNIX places us in a directory, called home
directory.
4. The most common file type is ordinary (or regular) file.
5. Command mode is the default mode of vi editor.
6. Bash (Bourne Again Shell) shell is the most common and best to
use.
7. do and done keywords are used in the while loop.
8. If there are special characters in a pattern, then we've to enclose
them in quotes (single or double).
Answers: 2023 Paper
9. UNIX was developed by Ken Thompson and Dennis Ritchie (at
AT&T Bell Labs).
10. The process of loading the Operating System into main
memory is called booting.
11. When a new process is created, this is called as forking (or
spawning).
12. In UNIX Operating System, 'Vi' is an editor (or text editor).
13. At the core of the UNIX Operating System Kernel exist that
process request of shell.
14. The command 'grep' stands for Global Regular Expression
Print.
8
15. The 'tr' command is used for translating or deleting
characters.
16. Two files can be merged based on a key using join command.
From 2024 Paper
17. What is a kernel?
The kernel is the core component of the UNIX operating system that
acts as a bridge between the software applications and the hardware. It
manages system resources, including CPU scheduling, memory
allocation, and peripheral device communication. Because it interacts
directly with the hardware, it is responsible for maintaining the
system's security and stability.
18. What is the default login shell? How to change it?
The default login shell is the command-line interface (usually Bash or
Sh) that starts automatically when a user logs in. You can change your
default shell using the chsh (change shell) command. Alternatively, a
superuser can change it by manually editing the user's entry in the
/etc/passwd configuration file.
19. What is the fork() system call?
The fork() system call is used in UNIX to create a new process, which is
called the child process. This child process is an exact copy of the
parent process, sharing the same environment and file descriptors but
possessing a unique Process ID (PID). It is the primary method of
process creation in UNIX.
20. Which command is used to find all information of the user?
The finger command is primarily used to display detailed information
about users, including login name, real name, and home directory.
Additionally, the id command provides numeric user and group IDs,
9
while the who command shows who is currently logged into the system
and their terminal information.
21. Which four fundamental components of every file system?
The four fundamental components of a UNIX file system are the Boot
Block (contains the boot loader), the Super Block (contains metadata
about the file system state), the Inode Table (stores file attributes and
pointers to data), and the Data Blocks (where the actual file content is
stored).
22. What is the lifespan of a shell variable?
The lifespan of a shell variable is limited to the current shell session in
which it was created. Once the user logs out or closes the terminal
window, the variable is destroyed. To make a variable persist or be
accessible to child processes, it must be exported using the export
command.
23. What is a system call?
A system call is a programmatic way in which a computer program
requests a service from the kernel of the operating system. It acts as an
interface between a process and the OS. Common examples include
requests for hardware-related services (like disk access), creation of
new processes, and communication with integral kernel services.
24. Write the syntax of the switch statement.
In UNIX Shell Scripting, the "switch" logic is implemented using the case
statement. The syntax is:
Bash
case $variable in
pattern1) commands ;;
pattern2) commands ;;
10
*) default_commands ;;
esac
It matches the variable against patterns and executes the
corresponding block until the double semicolon is reached.
25. Name some utility programs in Unix.
UNIX provides numerous utility programs for different tasks. Common
examples include grep for searching text patterns, sed for stream
editing, awk for data processing, sort for organizing file content, and cp
or mv for file management. These utilities can be combined using pipes
to perform complex operations.
26. What is the purpose of the "grep" utility?
The grep (Global Regular Expression Print) utility is used to search for
specific text patterns within files. It scans the input line by line and
prints any line that matches a specified regular expression. It is
essential for filtering logs, searching through codebases, and processing
large volumes of textual data efficiently.
From 2023 Paper
27. What ls command does? Write the syntax of ls command with all
applicable arguments.
The ls command lists information about files and directories within the
file system. The syntax is ls [options] [file/directory]. Common
arguments include -l for long listing (showing permissions and size), -a
to show hidden files, -h for human-readable sizes, and -R for recursive
listing of subdirectories.
28. If a command has the .txt extension, can it be executed?
11
In UNIX, a file's executability is determined by its file permissions, not
its extension. If a .txt file has the "execute" bit set (via chmod +x) and
contains a valid script (with a shebang like #!/bin/bash), it can be
executed. Unlike Windows, UNIX does not rely on extensions to define
file types.
29. How can you define PATH?
The PATH is an environment variable that tells the shell which
directories to search for executable files. It is defined as a colon-
separated list of directory paths. For example:
PATH=/usr/bin:/bin:/usr/local/bin. You can add new directories to it by
using the command export PATH=$PATH:/new/directory/path in your
profile script.
30. How do you find out the version number of your UNIX Operating
System?
The version number and general system information can be found using
the uname command. Specifically, uname -a provides all system
information, including the kernel version, release level, and hardware
architecture. Alternatively, checking files like /etc/issue or
/proc/version can provide more specific distribution details.
31. Is an option also an argument? How do an argument differ from
an option?
An option is a specific type of argument. Options usually start with a
dash (-) and modify the behavior of a command (e.g., -l in ls -l). In
contrast, a general argument usually refers to the target of the
command, such as a filename or a directory path upon which the
command operates.
32. State the syntax man command.
12
The man command is used to display the online reference manual
pages for commands and utilities. The basic syntax is man [options]
[section_number] command_name. For example, man 1 ls displays the
manual for the ls command from section 1. It provides details on
syntax, options, and exit codes.
33. Write the purpose of pwd, echo and date command.
The pwd (print working directory) command displays the full absolute
path of the current directory. The echo command is used to display a
line of text or the value of variables on the terminal. The date
command displays or sets the current system date and time in various
formats.
34. What is the significance of shell in UNIX? State any three shell
names.
The shell is a command-line interpreter that acts as the interface
between the user and the kernel. It allows users to execute commands
and write scripts to automate tasks. Significant shells include the
Bourne Shell (sh), the Bash (Bourne Again Shell), and the C Shell (csh).
35. State the three modes of operation used in 'Vi'.
The 'Vi' editor operates in three distinct modes: Command Mode
(default mode for moving the cursor and deleting text), Insert Mode
(used for typing and entering actual text into the file), and Ex Mode (or
Last Line Mode) (used for saving, quitting, and performing complex
search/replace operations).
36. What is the essence of chmod command?
The essence of the chmod (change mode) command is to manage file
security by defining who can read, write, or execute a file. It allows the
owner to set specific permissions for the User (owner), the Group, and
Others using either numeric (e.g., 755) or symbolic (e.g., u+x) notation.
13
From 2024 Paper
37. Differentiate between external and internal commands in Unix.
Internal commands (built-ins) are part of the shell's binary itself; they
execute directly within the shell process without spawning a new one,
making them very fast (e.g., cd, echo, pwd). External commands are
separate executable files stored on the disk, usually in /bin or /usr/bin.
When executed, the shell must locate them via the PATH variable and
create a new process (forking) to run them (e.g., ls, cat, grep).
38. What are system processes? Give an example.
System processes (often called daemons) are background processes
that start during system boot-up and run continuously to provide
essential services to the operating system or users. They are not
associated with any specific terminal or user session. An example is init
(or systemd), which is the first process to start and manages all other
processes, or sshd, which handles incoming remote login requests.
39. Why might you need to create partitions in Unix?
Partitions are created to divide a physical hard drive into multiple
independent logical sections. This is necessary for organizing data
(separating system files from user data), security (setting different
permissions per partition), and preventing system failure (if the /home
partition fills up, the / root partition remains functional). It also allows
for multiple operating systems to coexist on the same disk and
facilitates easier backups.
40. Describe the login process in Unix.
14
The login process begins when the init process spawns a getty process
for a terminal. getty displays the login prompt; once a username is
entered, it executes the login program. login asks for a password,
verifies it against the /etc/passwd (and /etc/shadow) file, and if
authenticated, it sets up the user environment and starts the user's
default shell (like Bash), placing them in their home directory.
41. What are hard links and symbolic links in Unix?
A hard link is a direct pointer to the inode of a file; it is essentially
another name for the same data. If the original file is deleted, the data
remains accessible through the hard link. A symbolic link (soft link) is a
special file that contains the path to another file as text, similar to a
shortcut. If the original file is deleted, a symbolic link becomes
"broken" and points to nothing.
42. Differentiate between $@ and $*.
Both are used to access all command-line arguments, but they differ
when enclosed in double quotes. "$*" treats the entire list of
arguments as a single string separated by the first character of the IFS
variable (usually a space). In contrast, "$@" treats each argument as a
separate quoted string. "$@" is generally preferred in scripts because it
preserves arguments that contain internal spaces correctly.
43. Tell us about the disadvantages of shell scripting.
While powerful, shell scripting has several drawbacks: it is slower than
compiled languages (like C++) because it is interpreted line-by-line. It
has limited debugging tools, making complex logic hard to
troubleshoot. Additionally, shell scripts often have poor portability
between different shell versions or UNIX flavors, and they lack
advanced data structures and high-performance capabilities required
for heavy computational tasks.
44. What is the main difference between BASH and DOS?
15
The main difference lies in their architecture and syntax. Bash (UNIX) is
case-sensitive, uses forward slashes (/) for directories, and treats
almost everything (including hardware) as a file. DOS (Windows) is
case-insensitive and uses backslashes (\) for paths. Furthermore, Bash
supports advanced features like piping, sophisticated scripting logic,
and background processing, whereas DOS was originally a single-
tasking system with very basic batch processing capabilities.
45. How does pattern matching work in Unix? Explain.
Pattern matching in UNIX is achieved through wildcards (globbing) or
regular expressions. Wildcards like * match zero or more characters,
and ? matches a single character. For example, ls *.txt finds all text files.
More advanced matching uses grep with Regular Expressions, where
characters like ^ (start of line) or $ (end of line) allow for precise
searching within the content of files based on complex text patterns.
46. What are functions and how are they defined and used?
Functions in shell scripting are modular blocks of code that perform a
specific task and can be reused multiple times. They are defined using
the syntax function_name() { commands; }. Once defined, a function is
"called" simply by using its name in the script. They help in reducing
code redundancy, improving readability, and allowing for local variable
management within a script's execution.
From 2023 Paper
47. Compare the command / and f.**
The pattern /* refers to all files and directories located in the root
directory of the system. In contrast, f* is a wildcard pattern that
matches any file or directory in the current working directory whose
name starts with the letter 'f'. While /* is an absolute path reference, f*
is a relative pattern used for filtering local filenames.
16
48. What the command mv does? Write the syntax of it.
The mv command is used to move or rename files and directories. If
the destination is a different directory, it moves the file; if the
destination is in the same directory with a different name, it renames
it.
Syntax: mv [options] source destination
Example: mv [Link] [Link] (Renaming) or mv [Link]
/home/user/ (Moving).
49. If mkdir foo command doesn't create foo directory, what could be
the possible reason?
The most common reasons include: 1) Permission Denied: The user
does not have 'write' permissions in the parent directory. 2) File Exists:
A file or directory named 'foo' already exists. 3) Read-Only File System:
The storage medium is mounted in read-only mode. 4) Space/Quota:
The disk is full or the user has exceeded their allocated disk quota.
50. State the two reasons for not having a file name beginning with a
hyphen.
First, UNIX commands treat strings starting with a hyphen as options
(e.g., -l or -a). If you try to delete a file named -file, rm will try to
interpret -f as an option and fail. Second, it makes command-line
processing extremely difficult and confusing, often requiring special
syntax (like rm -- -file) to bypass the shell's standard argument parsing.
51. What is Shell script? State the essence of Shell scripting in UNIX.
A shell script is a text file containing a sequence of UNIX commands
that the shell executes in order. The essence of shell scripting is
automation and efficiency. It allows users to combine simple
commands into complex workflows, automate repetitive administrative
17
tasks, and perform batch processing of data, significantly reducing
manual effort and the likelihood of human error.
52. What is the essence of umask command?
The umask (user file-creation mask) command determines the default
permissions assigned to newly created files and directories. It works as
a "filter" that subtracts permissions from the system maximum (666 for
files, 777 for directories). For example, a umask of 022 ensures that
new files are readable by everyone but writable only by the owner,
which is vital for system security.
53. Compare the command echo "$SHELL" with echo '$SHELL' in UNIX.
echo "$SHELL" uses double quotes, which allow variable expansion; it
will print the actual path of your shell (e.g., /bin/bash). echo '$SHELL'
uses single quotes, which treat everything as literal text; it will literally
print the string $SHELL on the screen without looking up its value. This
highlights the difference between weak and strong quoting.
54. What happens when you use the command cat file1 > file2.
This command uses output redirection. It reads the content of file1 and
writes it into file2. If file2 already exists, its previous content is
completely overwritten (erased). If file2 does not exist, the shell creates
it. This is a common way to copy the contents of one file into another
or to initialize a file with specific data.
55. What is the difference between directory='pwd' and
directory=pwd?
In directory='pwd', the single quotes treat pwd as a literal string, so the
variable directory will literally hold the text "pwd". In directory=pwd``,
the backticks trigger command substitution; the shell executes the pwd
command and assigns its output (the current path, like /home/user) to
the variable. (Note: Modern scripts prefer $(pwd) over backticks).
18
56. Write the syntax of grep command with all its options.
Syntax: grep [options] pattern [file...]
Common Options:
-i: Ignore case (case-insensitive search).
-v: Invert match (show lines that do not match).
-n: Show line numbers.
-c: Count the number of matching lines.
-l: List only the names of files with matches.
-r: Recursive search through directories.
LONG ANSWERS
19
57. Explain the architecture of the Unix system.
The architecture of the UNIX operating system is often described as a
layered structure, similar to the layers of an onion. This design ensures
a clear separation between the user's applications and the computer's
physical hardware. By organizing the system into distinct layers, UNIX
achieves high levels of stability, security, and portability.
1. The Hardware Layer
At the very center is the hardware layer. This includes the physical
components of the computer, such as the Central Processing Unit
(CPU), Random Access Memory (RAM), disk drives, and Input/Output
(I/O) devices. In UNIX, the hardware is never accessed directly by user
applications; instead, it is managed by the kernel to ensure that
multiple programs don't conflict while trying to use the same resource.
2. The Kernel
The kernel is the "heart" of the operating system. It is a specialized
program that remains in the main memory from the moment the
system boots until it shuts down. Its primary responsibilities include:
Process Management: Scheduling which program gets to use the
CPU and for how long.
Memory Management: Allocating RAM to various processes and
ensuring they don't interfere with each other's memory space.
File System Management: Handling how data is stored, retrieved,
and organized on disks.
Device Management: Acting as an intermediary between software
and hardware via device drivers.
3. The System Call Interface
20
Encapsulating the kernel is the System Call interface. This is a set of
"entry points" or functions that allow the shell and other applications
to request services from the kernel. For example, if a program needs to
read a file, it executes a read() system call, which the kernel then
processes.
4. The Shell
The shell is the environment in which users interact with the system. It
is a command-line interpreter that reads the commands typed by the
user and translates them into a language the kernel understands. The
shell is not part of the kernel; it is a utility program that sits on top of it.
Popular shells include Bash, CSH, and ZSH. It also provides a powerful
programming environment through shell scripting.
5. Application and Utilities Layer
The outermost layer consists of user applications, compilers (like GCC),
and system utilities (like ls, grep, and awk). These programs interact
with the shell or make direct system calls to perform specific tasks.
Because of this modularity, developers can write complex software
without needing to know the technical details of the underlying
hardware.
58. Describe the key features of Unix operating systems.
UNIX is a powerful, robust, and highly versatile operating system that
laid the foundation for modern computing. Its design philosophy, often
referred to as the "UNIX Philosophy," emphasizes simplicity and
modularity. Here are the key features that make UNIX unique:
1. Multi-user and Multi-tasking Capabilities
UNIX was designed from the ground up to allow multiple users to log in
and use the system's resources simultaneously. Each user has their own
21
private workspace and set of permissions. Furthermore, it is a multi-
tasking system, meaning it can execute multiple processes (tasks) at
once by sharing CPU time efficiently among them.
2. Hierarchical File System
UNIX uses a tree-like structure for organizing files and directories.
Everything starts from the "root" directory, denoted by a forward slash
(/). This organized structure makes it easy to locate files and maintain
system order. A famous feature of UNIX is that "Everything is a file"—
even hardware devices (like keyboards or hard drives) are represented
as files in the /dev directory.
3. Portability
Unlike earlier operating systems written in machine-specific assembly
language, UNIX was rewritten in the C language. This made it highly
portable, meaning it could be moved and compiled on different
hardware platforms with minimal changes. This feature is why UNIX
and its derivatives (like Linux) run on everything from supercomputers
to smartphones.
4. Shell and Scripting
The Shell is a unique feature that provides both an interactive
command interface and a programming language. Users can combine
simple commands into complex scripts to automate repetitive tasks.
The ability to "pipe" the output of one command into another (|)
allows for incredible flexibility in data processing.
5. Security and Permissions
UNIX provides a strong security model based on file permissions. Every
file and directory has an owner and belongs to a group. Permissions
(Read, Write, Execute) are strictly enforced for the Owner, the Group,
22
and others. This ensures that unauthorized users cannot access or
modify sensitive system files.
6. Rich Library of Utilities
UNIX comes with hundreds of small, specialized utility programs (like
sed, awk, grep, find). Following the UNIX philosophy, each tool does
"one thing and does it well." These tools can be linked together to solve
complex problems without writing new software from scratch.
59. What is the user and group in Unix? Explain related commands.
In the UNIX environment, resource management and security are built
around the concepts of Users and Groups. These entities define who
can access the system and what actions they are permitted to perform
on files and processes.
Understanding Users
A User is an individual who has an account on the UNIX system. Each
user is identified by a unique Username and a numeric User ID (UID).
Root User: The most powerful user is the 'root' (superuser), who
has UID 0. The root user has unrestricted access to all files and
commands.
Regular Users: Standard accounts created for people or specific
services. They have restricted access to ensure they don't
accidentally damage the system.
Understanding Groups
A Group is a collection of users who share similar access requirements.
For example, all users in a "Developers" group might need write access
to a specific source code directory. Each group has a Group Name and a
Group ID (GID). A user can be a member of multiple groups
simultaneously.
23
Related Commands
To manage users and groups, UNIX provides several essential
commands:
1. useradd / adduser: These commands are used by the system
administrator to create a new user account. It sets up the home
directory and initial environment files.
o Example: sudo useradd john
2. passwd: Used to change a user's password. Users can change their
own, but root can change anyone's password.
3. groupadd: This command creates a new group in the system.
o Example: sudo groupadd students
4. usermod: This is used to modify an existing user's account, such as
adding them to a specific group.
o Example: sudo usermod -aG students john (Adds John to the
students group).
5. chown (Change Owner): This command changes the ownership of
a file or directory. Only the root user can change a file's owner.
o Example: sudo chown john [Link]
6. chgrp (Change Group): This command changes the group
ownership of a file.
o Example: chgrp students [Link]
7. id: This command displays the UID and GID for the current user or
a specified user, showing exactly which groups they belong to.
8. who / whoami: who shows everyone currently logged into the
system, while whoami displays the username of the current
session.
24
By combining these commands with file permissions (Read, Write,
Execute), UNIX administrators can create a highly secure environment
where data is shared only with those who are authorized.
60. List and explain common user management commands in Unix.
User management is a critical aspect of UNIX system administration.
Because UNIX is a multi-user system, the operating system must
provide robust tools to create, modify, and delete user identities, while
also managing their access levels through groups and passwords. These
commands typically require "superuser" or sudo privileges because
they modify sensitive system files like /etc/passwd, /etc/shadow, and
/etc/group.
1. Creating and Deleting Users
useradd / adduser: The useradd command is the low-level utility
for creating a new user. It sets the user's home directory, UID, and
default shell. In many modern systems, adduser is a more user-
friendly script that prompts for information like the user's full
name and room number.
o Example: sudo useradd -m -s /bin/bash username (The -m flag
creates the home directory).
userdel: This command removes a user from the system. By
default, it only removes the user entry from the system files. To
delete the user's home directory and files as well, the -r (recursive)
flag is used.
2. Password Management
passwd: This is perhaps the most vital command for security. It
allows a user to change their password. When run by the root
25
user, it can be used to reset any user's password without knowing
the current one.
chage: This command is used to manage password aging. An
administrator can force a user to change their password every 90
days or lock an account after a certain date of inactivity.
3. Modifying User Attributes
usermod: This is a versatile command used to modify existing user
accounts. It can change a username, move a home directory, or
change the account's expiration date. One of its most common
uses is adding a user to a specific group using the -aG (append to
group) flags.
chsh: Short for "change shell," this allows a user or admin to
change the default command-line interface (e.g., switching from
sh to bash).
4. Group Management
groupadd: Creates a new group. Groups allow admins to assign
permissions to a set of users at once rather than individually.
groupdel: Removes a group from the system.
gpasswd: This is used to administer /etc/group. It can be used to
add or remove users from a group or define a group administrator.
5. Identity and Information Commands
id: This command provides the "who, what, and where" for a user.
It prints the UID, GID, and the names of all groups the user
belongs to.
who / w / whoami: who lists all users currently logged into the
system; w provides a more detailed view, including what processes
26
they are running; whoami simply tells you which user account you
are currently operating under.
finger: This utility provides a detailed profile of a user, including
their real name, last login time, and even their "plan" or "project"
file content if available.
61. Explain the different modes of operations used in vi editor.
The vi (Visual Instrument) editor is a "modal" editor. Unlike modern
word processors where you can type and use shortcuts simultaneously,
vi separates these tasks into distinct modes. This design allows for
extremely fast editing because your hands never have to leave the
home row of the keyboard to use a mouse or reach for arrow keys.
1. Command Mode
This is the default mode when you open a file. In this mode, almost
every key on the keyboard is a command rather than a character to be
typed.
Navigation: You use h, j, k, and l to move the cursor left, down, up,
and right.
Editing: Commands like x delete a single character, dd deletes a
whole line, and yy (yank) copies a line.
Transition: To enter Insert mode, you press i, a, or o. To enter Last
Line mode, you type a colon (:).
2. Insert Mode
This is the mode where you actually enter text. Once you press i (insert
before cursor) or a (append after cursor), every key you press is written
directly into the file.
27
Behavior: While in Insert mode, vi behaves like a standard text
editor.
Transition: To leave Insert mode and return to Command mode,
you must press the Esc key. This is a fundamental habit every vi
user develops.
3. Last Line Mode (Ex Mode)
When you are in Command mode and type a colon (:), the cursor jumps
to the very bottom of the screen. This is called Last Line Mode. It is
used for complex, "heavy-duty" commands.
Saving and Quitting: :w saves the file, :q quits, and :wq or :x saves
and quits.
Search and Replace: You can perform powerful global search and
replace operations here, such as :%s/old/new/g to replace all
instances of a word.
File Management: You can read another file into the current one
(:r filename) or run shell commands without leaving the editor (:!
ls).
4. Visual Mode (Optional but common)
Modern versions of vi (like vim) include a Visual Mode, triggered by
pressing v. This allows you to highlight blocks of text using movement
keys, which can then be deleted, copied, or formatted as a group.
The "essence" of vi is the constant switching between these modes.
While it has a steep learning curve, the efficiency it provides for
programmers and system administrators is unmatched, as it allows for
complex text manipulation with very few keystrokes.
62. What is a Shell? Types and Command Processing.
28
A Shell is a specialized program that serves as the interface between
the user and the Kernel. In the layered architecture of UNIX, the shell
sits around the kernel, protecting it from direct user contact while
providing a way for the user to execute programs and manage the
system.
Types of Shells
1. Bourne Shell (sh): The original UNIX shell developed by Stephen
Bourne. It is the standard for shell scripting due to its simplicity
and speed.
2. C Shell (csh): Developed at Berkeley, its syntax resembles the C
programming language. It is popular for interactive use but less
common for scripting.
3. Korn Shell (ksh): A powerful shell that combines features of both
the Bourne and C shells.
4. Bash (Bourne Again Shell): The most popular modern shell. It is an
enhanced version of the Bourne shell and is the default on almost
all Linux distributions.
5. Z Shell (zsh): An extension of Bash with even more features like
advanced auto-completion and themes.
How Commands are Processed
When you type a command (e.g., ls -l /home) and press Enter, the shell
goes through a four-step cycle:
1. Parsing: The shell breaks the command line into "tokens"—the
command name (ls), the options (-l), and the arguments (/home).
2. Expansion: The shell looks for wildcards (like *), variables (like
$HOME), or aliases and expands them into their full values.
29
3. Execution: The shell looks for the command. If it is "internal" (built
into the shell), it runs it immediately. If it is "external," the shell
uses the PATH variable to find the executable file, "forks" itself to
create a new process, and "execs" the command.
4. Wait: The shell usually waits for the command to finish before
displaying a new prompt to the user.
5. Write a shell script to receive student name, register number, and
marks, then calculate grade.
6. Write a shell script to receive student name, register number, and
marks, then calculate grade.
63. Shell Script for Student Grades
Bash
#!/bin/bash
# Receiving Input
echo "Enter Student Name:"
read name
echo "Enter Register Number:"
read reg_no
echo "Enter Marks for 3 Subjects:"
read m1 m2 m3
# Calculation
total=$((m1 + m2 + m3))
avg=$((total / 3))
# Grade Logic
if [ $avg -ge 90 ]; then
grade="A"
30
elif [ $avg -ge 75 ]; then
grade="B"
elif [ $avg -ge 50 ]; then
grade="C"
else
grade="F"
fi
# Output Result
echo "--------------------------"
echo "Student Report"
echo "Name: $name"
echo "Reg No: $reg_no"
echo "Total Marks: $total"
echo "Average: $avg"
echo "Grade: $grade"
echo "--------------------------"
64. Write the command for grep operations (floating point,
uppercase, etc.).
The grep (Global Regular Expression Print) command is one of the most
powerful text-processing tools in UNIX. It uses Regular Expressions (RE)
to find specific patterns within files. To handle complex patterns like
floating-point numbers or specific case types, we often use Extended
Regular Expressions with the grep -p or egrep command.
1. Finding Floating Point Numbers
To find a floating-point number, we need to look for a sequence of
digits, followed by a decimal point, followed by more digits. In a file
named [Link], the command would be:
31
grep -E "[0-9]+\.[0-9]+" [Link]
[0-9]+ matches one or more digits.
\. escapes the dot (otherwise, . matches any character).
[0-9]+ matches the fractional part.
2. Finding Uppercase Patterns
To find lines containing only uppercase words, we use character classes:
grep "[A-Z]" filename
To find lines that start with an uppercase letter:
grep "^[A-Z]" filename
3. Case-Insensitive Search
If you want to find a word regardless of whether it is uppercase or
lowercase, use the -i option:
grep -i "unix" filename (This matches "UNIX", "Unix", "unix", etc.)
4. Whole Word Search
To find a pattern that is a standalone word (not part of a larger word),
use the -w flag:
grep -w "is" filename (This prevents matching "this" or "island").
65. What is a process? Explain how shell plays a vital role in process
creation and its phases.
A process is an instance of a program in execution. While a "program"
is a passive entity (like a file stored on a disk), a "process" is an active
32
entity that consumes system resources like CPU time, memory, and I/O
addresses. Every process in UNIX is identified by a unique Process ID
(PID).
The Role of the Shell in Process Creation
The shell acts as the primary manager for process creation. When a
user types a command, the shell does not "run" the command inside
itself. Instead, it acts as a parent that facilitates the birth of a new
process. It manages the environment, handles input/output
redirection, and decides whether the process should run in the
foreground (blocking the shell) or background (using &).
Phases of Process Creation
Process creation in UNIX follows a very specific sequence known as the
Fork-Exec model:
1. The Fork Phase: The existing process (the Shell) calls the fork()
system call. This creates an exact "child" copy of the shell. At this
moment, two identical processes are running the same code.
2. The Exec Phase: The child process immediately calls the exec()
system call. This replaces the child’s memory with the code of the
new program (e.g., ls or grep). The PID remains the same as the
fork, but the "brain" of the process is now the new command.
3. The Wait Phase: By default, the parent process (Shell) calls wait().
It pauses its own execution until the child process finishes and
returns an "exit status."
4. The Termination Phase: When the command finishes, it calls
exit(). The kernel cleans up its resources, and the shell wakes up to
display the prompt again.
33
66. Explain at least 3 commands from each category of commands
recognized by the shell.
UNIX commands are generally categorized by their function. Here are
three categories with three commands each:
Category 1: File Management Commands
These commands allow users to navigate and manipulate the file
system hierarchy.
1. cp (Copy): Used to duplicate files or directories.
o Syntax: cp [options] source destination
o Example: cp [Link] [Link]
2. mv (Move/Rename): Moves a file to a new location or renames it.
o Syntax: mv source destination
o Example: mv [Link] [Link]
3. rm (Remove): Deletes files or directories.
o Syntax: rm -r directory_name
o Example: rm -f [Link]
Category 2: Directory Management Commands
These are used specifically for handling folders (directories).
1. mkdir (Make Directory): Creates a new folder.
o Syntax: mkdir directory_name
o Example: mkdir Project_Alpha
2. pwd (Print Working Directory): Shows the current absolute path.
o Syntax: pwd
o Example: Output might be /home/user/docs
34
3. cd (Change Directory): Navigates between folders.
o Syntax: cd [path]
o Example: cd .. (moves to the parent directory).
Category 3: Content Processing Commands
These are used to view or filter the data inside files.
1. cat (Concatenate): Displays the entire content of a file.
o Syntax: cat filename
o Example: cat [Link]
2. head: Displays the first few lines of a file (default 10).
o Syntax: head -n [number] filename
o Example: head -n 5 [Link]
3. wc (Word Count): Counts lines, words, and characters.
o Syntax: wc -l filename (counts lines).
o Example: wc -w [Link]
67. How do you copy all directories and files from the current
directory to its parent directory?
To copy everything from the current directory to the parent directory,
you must use the cp command with specific flags and path symbols. In
UNIX, the current directory is represented by a single dot (.) and the
parent directory is represented by two dots (..).
The Command
cp -r ./* ..
Detailed Explanation
cp: The command for copying.
35
-r (Recursive): This flag is the most important part. Without it, cp
will only copy files and will ignore all folders/directories. The
recursive flag tells UNIX to go inside every folder and copy its
contents as well.
./*: This uses the wildcard * to match every file and directory
inside the current location (./).
..: This specifies the destination. The two dots tell the shell to
move up one level in the file system hierarchy.
Important Considerations
1. Hidden Files: Note that the * wildcard usually does not match
hidden files (those starting with a dot, like .bashrc). To include
them, you might need to use cp -r . .. (depending on the shell
version) or a more specific globbing pattern.
2. Overwrite Warning: If the parent directory already contains files
with the same names, this command will overwrite them without
asking. To be safe, you can add the -i (interactive) flag: cp -ri ./* ...
3. Avoiding Infinite Loops: Some shells are smart enough to realize
you are copying a directory into its parent, but you should ensure
you aren't trying to copy the current directory into itself, which
can cause errors.
68. State and explain three ways to know your home directory.
The home directory is the private space assigned to a user upon
account creation. In UNIX, there are several environment variables and
shortcuts to identify this path.
36
1. Using the echo $HOME Command:
The $HOME environment variable is automatically set by the
system during the login process. It stores the absolute path of the
current user's home directory. By using the echo command, you
can display the value stored in this variable.
o Example: echo $HOME (Output typically looks like
/home/username).
2. Using the Tilde (~) Shortcut with pwd:
In most UNIX shells, the tilde symbol (~) is a reserved shortcut that
represents the home directory. If you change your location to the
home directory using cd ~ and then type pwd (Print Working
Directory), the system will display the full path.
o Example: cd ~; pwd
3. Using the getent or grep on /etc/passwd:
The system configuration file /etc/passwd contains essential user
account information. The sixth field of each entry in this file
specifies the home directory. You can search for your username to
find your assigned path.
o Example: grep "^$USER" /etc/passwd | cut -d: -f6
o Alternatively, simply typing cd without any arguments will always
return you to your home directory, and you can then verify the
location with pwd.
69. Write the command for operations (match filenames, count users,
remove files).
1. Match Filenames (using Wildcards):
To match filenames based on a pattern, we use shell globbing. For
example, to list all files starting with "test" and ending in ".sh":
37
o Command: ls test*.sh
2. Count Users:
To count the number of users currently logged into the system, we
pipe the output of the who command into the word count (wc)
utility with the line flag (-l).
o Command: who | wc -l
3. Remove Files:
The rm command is used for deletion. To remove a specific file:
o Command: rm [Link]
o To remove multiple files matching a pattern (e.g., all .tmp files): rm
*.tmp
70. Shell script to convert file contents to uppercase.
This script iterates through all arguments provided, checks if they are
valid files, and uses the tr (translate) command to convert the text to
uppercase.
Bash
#!/bin/bash
# Check if arguments are provided
if [ $# -eq 0 ]; then
echo "Usage: $0 file1 file2 ..."
exit 1
fi
38
# Loop through each file provided as an argument
for file in "$@"
do
if [ -f "$file" ]; then
echo "Converting $file to uppercase..."
# Translate lower to upper and save to a temporary file
tr '[a-z]' '[A-Z]' < "$file" > "$[Link]"
# Overwrite original file with uppercase content
mv "$[Link]" "$file"
else
echo "Error: $file is not a valid file."
fi
done
71. Search a pattern with grep, sed, and awk and test return values.
In UNIX, a command returns 0 for success (pattern found) and a non-
zero value (usually 1) for failure (pattern not found). You can check this
using the $? variable.
1. Using grep:
o Command: grep "pattern" [Link]
o Test failure: grep "nonexistent" [Link]; echo $? (Returns 1)
2. Using sed:
o Command: sed -n '/pattern/p' [Link]
o Test failure: sed -n '/nonexistent/p' [Link]; echo $? (Note: sed
often returns 0 as long as the command syntax is correct, even if
no match is found. To test for a match, you must check if the
output is empty).
3. Using awk:
39
o Command: awk '/pattern/' [Link]
o Test failure: awk '/nonexistent/' [Link]; echo $? (Like sed, awk
returns 0 if the script executes correctly, regardless of matches.
For custom exit codes, use: awk '/pattern/ {found=1} END {if (!
found) exit 1}' [Link]).
72. Shell script to count occurrences of a pattern in files.
This script takes the first argument as the pattern and the remaining
arguments as the filenames to search through.
Bash
#!/bin/bash
# Ensure at least two arguments (pattern and one file)
if [ $# -lt 2 ]; then
echo "Usage: $0 pattern filename1 [filename2 ...]"
exit 1
fi
pattern=$1
shift # Remove the pattern from the argument list
# Loop through the remaining arguments (filenames)
for file in "$@"
do
if [ -f "$file" ]; then
# -o prints only matching parts, wc -l counts them
count=$(grep -o "$pattern" "$file" | wc -l)
40
echo "The pattern '$pattern' appears $count times in $file."
else
echo "File $file not found."
fi
done
73. What is Unix OS? Explain the Features of Unix OS.
UNIX is a powerful, multi-user, multi-tasking operating system originally
developed in 1969 by a group of AT&T employees at Bell Labs, including
Ken Thompson and Dennis Ritchie. Unlike previous operating systems
that were tied to specific hardware, UNIX was rewritten in the C
programming language in 1973, making it the first truly portable
operating system. It provides an environment where multiple users can
execute multiple programs simultaneously while sharing system
resources efficiently.
Key Features of UNIX OS:
1. Multi-user Capability:UNIX allows multiple users to log into the
system at the same time and run different programs. Each user is
assigned a unique identity, and the operating system ensures that
one user's activities do not interfere with another’s. This is
managed through a sophisticated system of permissions and
ownership.
2. Multi-tasking:UNIX can execute more than one task at a time for a
single user or multiple users. It uses time-sharing techniques
where the CPU switches rapidly between processes, giving each
the illusion of continuous execution. Users can also run processes
in the background while continuing to work in the foreground.
3. Hierarchical File System:UNIX uses a tree-like structure to
organize files and directories. Starting from the root (/), all files
41
and subdirectories branch out. This logical organization makes it
easy to maintain thousands of files and provides a standardized
way to access data.
4. Everything is a File:One of the most profound features of UNIX is
the treatment of hardware devices (printers, disks, keyboards) as
files. This allows the same tools used for reading and writing text
files to be used for interacting with hardware, simplifying the
system's architecture.
5. Pipes and Filters:UNIX introduced the concept of Pipes (|), which
allows the output of one command to serve as the input for
another. This enables users to string together simple, specialized
"Filter" commands (like grep, sort, uniq) to perform complex data
processing tasks without writing new programs.
6. Portability: Because UNIX is written in C, it is not hardware-
dependent. It can be moved (ported) from one machine
architecture to another with very little modification. This led to its
widespread adoption in servers, workstations, and eventually
mobile devices (via Android/iOS).
7. Security: UNIX provides a robust security model. Every file has
three types of permissions: Read, Write, and Execute, defined for
three categories of users: the Owner, the Group, and Others. This
ensures that sensitive system files are protected from
unauthorized access or accidental deletion.
8. The Shell:The Shell is a unique command-line interpreter that acts
as the interface between the user and the kernel. It is also a
powerful programming language in its own right, allowing users to
write scripts to automate complex sequences of tasks.
74. Define Architecture of Unix OS.
42
The architecture of UNIX is designed as a modular, layered system. This
design ensures that the user is isolated from the complexities of the
hardware, providing a stable and secure computing environment. The
architecture is typically visualized as four concentric layers.
1. The Hardware Layer:
At the center of the system lies the physical hardware. This includes the
CPU (processor), the RAM (main memory), disk controllers, and various
input/output devices. In UNIX, the hardware is a "slave" to the Kernel;
no user or application can touch the hardware directly.
2. The Kernel:
The Kernel is the "heart" of the operating system. It is the only part of
the system that interacts directly with the hardware. Its primary
functions include:
Memory Management: Keeping track of which parts of memory
are currently being used and by whom.
Process Management: Creating, executing, and terminating
processes. It manages CPU scheduling to ensure all tasks get fair
processing time.
File Management: Translating requests for files into physical disk
addresses.
I/O Management: Controlling the flow of data to and from
peripheral devices.
3. The System Call Interface:
This is the boundary between the Kernel and the rest of the system.
System calls are a set of specialized functions that allow the shell and
user applications to request services from the kernel. For example,
when a user types cat file, the command uses the open() and read()
system calls to ask the kernel for the data.
43
4. The Shell:
The Shell is the environment that surrounds the kernel. It is a
command-line interpreter that reads user commands and interprets
them into system calls. The Shell is often called the "User Interface" of
UNIX. It also handles variable expansion, wildcard matching, and the
redirection of input/output.
5. User Applications and Utilities:
The outermost layer consists of the tools and programs that users
actually use. This includes:
System Utilities: Standard commands like ls, grep, awk, sed, and
cp.
Compilers: Tools like gcc for C programming.
User Applications: Databases, web servers, and text editors (like vi
or emacs).
This layered approach is why UNIX is so stable. If a user application
crashes, it happens in the outermost layer. The Kernel, protected by the
Shell and System Call layers, remains unaffected, preventing the entire
system from crashing.
75. Define Files & Different Types of Files.
In the UNIX philosophy, the concept of a "file" is broader than in other
operating systems. A file is essentially a container for storing
information, but in UNIX, a file can represent anything from a simple
text document to a hard drive or a network connection. This uniform
treatment allows the OS to use a single set of tools to manage the
entire system.
Categories of Files in UNIX:
44
UNIX categorizes files into three main types, each serving a specific
purpose in the system's hierarchy.
1. Ordinary Files (Regular Files):
These are the most common files on a UNIX system. They contain data,
such as text, images, or executable programs. Ordinary files are divided
into two sub-types:
Text Files: These contain only readable characters (ASCII or
Unicode) and can be viewed or edited using tools like vi or cat.
Examples include source code (.c, .sh) and configuration files.
Binary Files: These contain data in a format that only the
computer can understand. They often represent compiled
programs or images. If you try to view a binary file with cat, you
will see unreadable symbols.
2. Directory Files:
In UNIX, a directory is actually a special type of file. Instead of
containing data like a text file, a directory file contains a list of
"filenames" and their corresponding Inode numbers (pointers to the
actual data).
Directories provide the structure for the hierarchical file system.
Every directory contains at least two entries: . (the current
directory) and .. (the parent directory).
Users can create subdirectories to organize their work, but the
system treats the directory itself as a file that can be read but only
modified by the kernel.
3. Special Files (Device Files):
45
These files represent physical hardware devices. By representing
hardware as files in the /dev directory, UNIX allows users to send data
to hardware using simple redirection. Special files are divided into:
Character Special Files: These represent devices that transfer data
one character at a time, such as a keyboard, mouse, or terminal.
They are accessed "serially."
Block Special Files: These represent devices that transfer data in
large blocks (usually 512 bytes or more), such as hard drives or CD-
ROMs. They allow for "random access" to data.
4. Other Specific Types:
Symbolic Links (Soft Links): These are files that act as pointers or
shortcuts to other files.
Named Pipes (FIFOs): Used for inter-process communication,
allowing two unrelated processes to exchange data.
Sockets: Used for network communication between different
machines or processes.
Here are the detailed responses for your final set of 8-mark questions.
These answers are structured to provide the technical depth and
specific examples required for exam purposes.
76. Explain Creating, Copying, Renaming & Deleting a File with Syntax
& Example.
In UNIX, file management is performed primarily through the command
line. These operations are fundamental to interacting with the
hierarchical file system.
1. Creating a File
46
There are several ways to create a file, but the most common are using
touch, cat, or a text editor like vi.
Method A (touch): Used to create an empty file.
o Syntax: touch filename
o Example: touch [Link]
Method B (cat with redirection): Used to create a file and add
content immediately.
o Syntax: cat > filename (Type content, then press Ctrl+D to
save).
o Example: cat > [Link]
2. Copying a File (cp)
The cp command makes an exact duplicate of a source file to a
destination.
Syntax: cp [options] source_file destination_file
Common Option: -r for copying directories recursively.
Example: cp [Link] report_backup.txt (Copies [Link] to a
new file named report_backup.txt).
3. Renaming a File (mv)
In UNIX, there is no separate "rename" command; the "move" (mv)
command is used for both moving files to different directories and
renaming them within the same directory.
Syntax: mv [options] old_name new_name
Example: mv [Link] final_notes.txt (Renames [Link] to
final_notes.txt).
4. Deleting a File (rm)
47
The rm (remove) command deletes files from the system. Warning: In
UNIX, there is no "Recycle Bin"; once a file is deleted with rm, it is
permanently gone.
Syntax: rm [options] filename
Common Options: -i (interactive, asks before deleting) and -f
(force delete).
Example: rm -i old_data.log
77. What is Unix File System? Explain different blocks of Unix.
The UNIX File System (UFS) is a logical method of organizing and
storing large amounts of data so that it can be easily managed and
retrieved. Physically, the file system is stored on a disk partition, which
the kernel divides into a series of logical blocks.
The Four Blocks of the UNIX File System:
1. Boot Block:
This is the first block of the file system (usually Block 0). It contains a
small program called the "bootstrap loader" or "bootloader." When the
computer is turned on, the hardware reads this block to load the kernel
into memory and start the operating system. Every file system has a
boot block, even if it doesn't contain a bootable OS.
2. Super Block:
This block contains the metadata that describes the state of the entire
file system. It keeps track of the file system's size, the number of free
blocks available, the number of free inodes, the status of the file
system (clean or dirty), and the disk's physical name. If the super block
is corrupted, the file system cannot be mounted.
3. Inode Block (Inode Table):
48
Following the super block is the Inode Table. Every file or directory in
UNIX has an associated Inode (index node). An inode is a data structure
that contains all information about a file except its name and actual
content. It stores:
o File type (ordinary, directory, etc.)
o Owner ID and Group ID
o Permissions (Read, Write, Execute)
o File size and timestamps (Created, Modified, Accessed)
o Pointers to the data blocks where the actual content is
stored.
4. Data Block:
This is the largest part of the file system. It contains the actual data of
the files and the content of the directories. When a file grows, the
kernel assigns more data blocks to it from the pool of free blocks listed
in the super block.
78. State & Explain Hard Link & Symbolic Link.
Links in UNIX allow a single file to be referred to by multiple names,
which is useful for organizing data without duplicating large files.
1. Hard Link
A hard link is an additional directory entry for an existing file. It points
directly to the Inode of the original file.
Mechanism: Both the original filename and the hard link share the
same Inode number.
Independence: If you delete the original file, the data still exists
and is accessible via the hard link. The data is only deleted when
the last hard link is removed.
49
Limitations: Hard links cannot span across different file systems
(partitions) and cannot be created for directories (to prevent
loops).
Command: ln original_file link_name
2. Symbolic Link (Soft Link)
A symbolic link is a special file that contains the path to another file
(like a shortcut in Windows).
Mechanism: It has its own unique Inode number. The content of
this link is simply the address/path of the target file.
Dependency: If the original file is deleted, the symbolic link
becomes "broken" or "orphaned" because it points to a path that
no longer exists.
Flexibility: Symbolic links can point to directories and can span
across different file systems or even different physical disks.
Command: ln -s original_file link_name
79. Define types of users in Unix.
UNIX is a multi-user system where security is maintained by
categorizing users into specific levels of authority. These levels
determine what files they can see and what system-wide changes they
can make.
1. Root User (Superuser)
The root user is the system administrator who has total control over
the entire operating system.
Identification: The root user always has a User ID (UID) of 0.
50
Privileges: Root can read, write, or delete any file on the system,
regardless of its permissions. Root can also create new users,
install software, and shut down the system.
Prompt: By default, the shell prompt for a root user is a hash sign
(#).
2. Regular User (Normal User)
These are the accounts created for people to perform daily tasks like
word processing, programming, or browsing.
Identification: These users have UIDs starting from 100 or 1000
(depending on the UNIX version).
Privileges: A regular user has full control over their own Home
Directory (/home/username) but cannot modify system files or
access other users' private files without permission.
Prompt: The shell prompt for a regular user is usually a dollar sign
($).
3. System User (Service User)
These accounts are not meant for human login. They are used by the
operating system to run specific services (daemons) with limited
privileges.
Purpose: By running a service (like a web server or mail server) as
a specific system user rather than "root," the system remains
secure. If the web server is hacked, the attacker only gains the
limited permissions of the www-data user, not full root access.
Examples: bin, mail, lp (for printing), and nobody.
4. Group Users
Users can be organized into Groups. A group is a logical collection of
users who share the same access needs. For example, all members of a
51
"Finance" group can be given write access to a budget spreadsheet,
while "Others" can only read it. Every user belongs to at least one
primary group.
Here are the detailed responses for your final set of 8-mark questions
regarding the Shell and the VI editor.
80. State & Explain concepts of Shell in Unix.
The Shell is one of the most vital components of the UNIX operating
system. It acts as a command-line interpreter that serves as an
interface between the user and the Kernel. Since the Kernel is the core
of the OS and handles hardware directly, the Shell provides a safe
environment for users to send instructions to the system.
Core Concepts of the Shell:
1. Command Execution:
The primary job of the shell is to wait for user input, parse the
command, and execute it. When you type a command like ls, the shell
searches for that executable in the system's PATH, creates a new
process, and displays the result.
2. Environment Customization:
The shell maintains an "environment" for the user. This includes
variables like $USER (your login name), $PATH (where the shell looks for
programs), and $PWD (your current directory). Users can customize
their shell experience by modifying these variables.
3. Input/Output Redirection:
The shell allows users to change where a command gets its input from
and where it sends its output.
52
o Standard Output (>): Redirects results to a file instead of the
screen.
o Standard Input (<): Takes input from a file instead of the
keyboard.
4. Pipes (|):
One of the most powerful concepts in UNIX is the pipe. It allows the
output of one command to be fed directly as the input to another
command, enabling the creation of complex workflows from simple
tools.
5. Programming (Shell Scripting):
The shell is not just an interface; it is a full programming language. It
supports loops, conditional statements (if/else), and variables. This
allows users to write "scripts" to automate repetitive administrative
tasks.
6. Wildcard Expansion (Globbing):
The shell interprets special characters like * (matches any string) and ?
(matches any single character). This allows users to perform operations
on groups of files easily, such as rm *.tmp.
81. What is VI editor in Unix? Explain Command Mode.
The VI editor (short for Visual Instrument) is a powerful, screen-based
text editor found on almost every UNIX and Linux distribution. It was
created by Bill Joy in 1976. Unlike modern "What You See Is What You
Get" editors, VI is modal, meaning it operates in different modes to
separate text entry from text manipulation.
Understanding Command Mode:
53
Command Mode is the default mode of the VI editor. When you first
open a file with the command vi filename, you are placed in Command
Mode.
Purpose: This mode is used for navigating the file, deleting text,
copying/pasting, and switching to other modes. You cannot type
text directly into the file while in this mode.
Navigation: Instead of using arrow keys (which were not common
on old terminals), VI uses the home-row keys:
o h (left), j (down), k (up), l (right).
Common Commands:
o x: Deletes the character under the cursor.
o dd: Deletes (cuts) the entire current line.
o yy: "Yanks" (copies) the current line.
o p: "Puts" (pastes) the last deleted or copied text after the
cursor.
o u: Undoes the last action.
Switching Modes: To leave Command Mode and start typing, you
press i (Insert) or a (Append). To return to Command Mode from
any other mode, you must press the Esc key.
82. State & Explain Shell Variable in Unix? Explain it briefly.
A Shell Variable is a named location in memory that stores a value used
by the shell or by a program during its execution. Variables allow users
to store data, such as paths, preferences, or calculation results, and
reuse them throughout a session or a script.
Types of Shell Variables:
54
1. System (Environment) Variables:
These are predefined by the system and are usually written in
UPPERCASE. They define the user's working environment.
o $HOME: The path to your home directory.
o $SHELL: The path to the current shell being used.
o $USER: The name of the logged-in user.
2. User-Defined Variables:
Users can create their own variables for scripts or temporary use. By
convention, these are often written in lowercase.
o Assignment: my_name="John" (Note: There are no spaces
around the = sign).
o Accessing: To see the value, you use the $ symbol: echo
$my_name.
3. Special Variables:
These are used primarily in shell scripting to handle command-line
arguments.
o $0: The name of the script.
o $1, $2, etc.: The first and second arguments passed to the
script.
o $#: The number of arguments provided.
Brief Characteristics:
Scope: Variables are usually local to the shell where they are
created. To make a variable available to child processes (sub-
shells), the export command is used (e.g., export my_var).
55
Persistence: Shell variables are temporary. Once the shell session
is closed, the variables are deleted unless they are defined in a
configuration file like .bashrc.
83. Define Save & Quit Option in VI Editor.
In the VI editor, saving changes and exiting the program is handled in
Last Line Mode (also known as Ex Mode). To enter this mode from
Command Mode, you must type a colon (:). The cursor will move to the
bottom left of the screen, allowing you to enter administrative
commands.
Common Save and Quit Commands:
1. :w (Write):
This saves the changes made to the file but keeps the editor open. It is
similar to clicking "Save" in a modern app.
o Variant: :w new_filename saves the content into a new file
without changing the original.
2. :q (Quit):
This exits the editor. However, if you have made changes that haven't
been saved yet, VI will prevent you from quitting and display an error
message.
3. :wq (Write and Quit):
This is the most common command used. it saves all changes and
immediately exits the editor back to the shell prompt.
o Shortcut: You can also use the command ZZ (capitalized) in
Command Mode to achieve the same result without typing
the colon.
4. :q! (Force Quit):
56
This command is used to exit the editor without saving any changes.
The exclamation mark (!) tells VI to ignore the fact that there are
unsaved modifications. This is useful if you made a mistake and want to
revert to the last saved version.
5. :x (Exit):
Similar to :wq, but it only writes the file if changes have actually been
made. If the file hasn't been modified, it simply quits.
84. Define Different Delete Options in VI Editor.
In the VI editor, deletion is an efficient process performed primarily in
Command Mode. Unlike standard editors where you hold down the
backspace key, VI provides specialized shortcuts to delete characters,
words, or entire blocks of text with minimal keystrokes.
1. Character Deletion:
x: Deletes the character directly under the cursor.
X: Deletes the character to the left of the cursor (similar to
Backspace).
2. Word Deletion:
dw: Deletes from the current cursor position to the beginning of
the next word.
db: Deletes the word backward from the cursor position.
3. Line Deletion:
dd: Deletes the entire current line.
D or d$: Deletes from the current cursor position to the end of the
line.
d0: Deletes from the cursor position back to the start of the line.
57
4. Multi-item Deletion:
VI allows you to prefix a command with a number to repeat it.
5dd: Deletes five lines starting from the current line.
3dw: Deletes the next three words.
Note: In VI, "deleting" is technically "cutting." Any text deleted is stored
in a temporary buffer and can be pasted elsewhere using the p (put)
command.
85. What is grep command? Explain with Syntax and Options.
The grep (Global Regular Expression Print) command is a powerful
administrative utility used to search for a specific pattern of characters
within files. It scans the input line by line and displays every line that
contains a match for the specified pattern.
Syntax:
grep [options] pattern [file_name]
Commonly Used Options:
1. -i (Ignore Case): Searches for the pattern regardless of whether it
is uppercase or lowercase.
o Example: grep -i "unix" [Link] matches "UNIX", "Unix", and "unix".
2. -v (Invert Match): Displays all lines that do not contain the
specified pattern.
3. -n (Line Number): Displays the line number in the file where the
match was found.
4. -c (Count): Instead of showing the lines, it simply displays the total
number of lines that matched.
58
5. -l (List Files): Displays only the names of the files containing the
pattern, not the matching lines themselves.
6. -w (Word): Matches the pattern as a whole word only (prevents
matching "is" inside "this").
86. What is Function in Shell?
A Function in a shell script is a reusable block of code that performs a
specific task. Instead of writing the same code multiple times in a
script, you can define it once as a function and "call" it whenever
needed. This makes scripts more organized, readable, and easier to
maintain.
Key Characteristics:
Definition: A function must be defined before it can be used in a
script.
Local Variables: Functions can have their own variables that do
not affect the rest of the script.
Positional Parameters: Functions accept arguments just like a
main script, using $1, $2, etc.
Syntax:
Bash
function_name() {
# commands to execute
echo "This is a function"
}
Example:
Bash
59
# Define function
welcome() {
echo "Hello $1, welcome to Unix Shell!"
}
# Call function
welcome "John"
87. Explain Loop Concepts in Shell (While, For, Until).
Loops are used to execute a set of commands repeatedly as long as a
certain condition is met.
1. For Loop
The for loop operates on a list of items. It repeats the commands once
for every item in the list.
Syntax:
Bash
for var in list; do
commands
done
Example: for i in 1 2 3; do echo $i; done
2. While Loop
The while loop continues to execute as long as the specified condition
remains true.
Syntax:
Bash
while [ condition ]; do
commands
done
60
Example: Counting from 1 to 5.
3. Until Loop
The until loop is the opposite of the while loop. It continues to execute
as long as the specified condition is false, stopping only when the
condition becomes true.
Syntax:
Bash
until [ condition ]; do
commands
done
88. Explain If-Else & Case Statements.
These are decision-making statements used to control the flow of a
script based on specific conditions.
1. If-Else Statement
The if statement checks a condition. If it is true, the then block
executes; if false, the else block executes.
Syntax:
Bash
if [ condition ]; then
# code if true
else
# code if false
fi
2. Case Statement
The case statement is a multi-way branch. It is a cleaner alternative to
multiple if-elif statements when comparing a single variable against
several different values (patterns).
61
Syntax:
Bash
case $variable in
pattern1)
commands ;;
pattern2)
commands ;;
*)
default_commands ;;
esac
Example: A menu-driven script where a user picks option 1, 2, or
3.