0% found this document useful (0 votes)
4 views50 pages

Unix and Shell Programming Lab Manual (1)...

The document is a lab manual for the UNIX and Shell Programming course at George College, Kolkata, detailing laboratory rules, practical assignments, and command usage. It includes instructions for students and teachers, a syllabus of practical tasks, and definitions of various UNIX commands. The objective is to familiarize students with essential UNIX commands for file management, system information, and shell scripting.

Uploaded by

graj06371
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)
4 views50 pages

Unix and Shell Programming Lab Manual (1)...

The document is a lab manual for the UNIX and Shell Programming course at George College, Kolkata, detailing laboratory rules, practical assignments, and command usage. It includes instructions for students and teachers, a syllabus of practical tasks, and definitions of various UNIX commands. The objective is to familiarize students with essential UNIX commands for file management, system information, and shell scripting.

Uploaded by

graj06371
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
You are on page 1/ 50

George College, Kolkata

LAB MANUAL

Bachelor of Computer Applications


NAME: Pratoy ghosh
ROLL: 13301221019
REG NO. :211331001210012
Semester : 6TH

Subject: UNIX AND SHELL PROGRAMMING LAB

Course Code : BCAC691

VER. 2024
DOs and DON’Ts in Laboratory:

1. Make entry in the Log Book as soon as you enter the Laboratory.

2. All the students should sit according to their roll numbers starting from their
left to right.
3. All the students are supposed to enter the terminal number in the log book.
4. Do not change the terminal on which you are working.
5. All the students are expected to get at least the algorithm of the
program/concept to be implemented.
6. Strictly observe the instructions given by the teacher/Lab Instructor.
7. Do not disturb machine Hardware / Software Setup.

VER. 2024
Instruction for Laboratory Teachers:

1. Submission related to whatever lab work has been completed


should be done during the next lab session along with signing the
index.

2. The promptness of submission should be encouraged by way of


marking and evaluation patterns that will benefit the sincere
students.

3. Continuous assessment in the prescribed format must be followed.

VER. 2024
LAB SYLLABUS
List of Practical:
1. Calendar, Display system date, Message display, Calculator, Password changing,
Knowing who are logged in, Knowing System information
2. Displaying pathname of the current directory (pwd), Changing the current directory
(cd), Make directory (mkdir), Remove directories (rmdir), Listing contents of directory (ls
and its options), Absolute pathname, Relative pathname, Using dot (.) and dotdot (..)
3. Displaying and creating files, Copying a file, Deleting a file, Renaming/ moving a file,
Paging output, Knowing file type, Line, word and character counting (wc), Comparing files,
Finding common between two files, Displaying file differences
4. File and directory attributes listing, File ownership, File permissions, Changing file
permissions – relative permission &absolute permission, Changing file ownership,
Changing group ownership, File system and inodes, Hard link, Soft link, Default
permissions of file and directory and using umask, Listing of modification and access time,
Time stamp changing, File locating
5. Types of shell, Pattern matching, Escaping, Quoting, Redirection, Pipe, tee, Command
substitution, Shell variables
6. Display process attributes, Display System processes, Background jobs, Reduce priority,
Sending job to background and foreground, Listing jobs
7. Prepare file for printing, Custom display of file using head and tail, Vertical division of
file, Paste files, Sort file, Finding repetition and non- repetition, Manipulating characters
using, Searching pattern
8. Introduction to VI/VIM editor, Different commands of the editor, File editing in the editor
9. Simple shell scripts, Interactive shell script, Using command line arguments, Logical
operator (&&, ||), Condition checking (if-then, if-then-else-fi, if-then—elif-else-fi, case),
Expression evaluation (test, []), Computation (expr), Using expr for strings, Loop (while,
for, until, continue), Use of positional parameters
10. Simple implementation of basic LINUX commands, utilities, filters etc. using shell
scripts

VER. 2024
Prerequisites:

Basic understanding of Unix/Linux terminal navigation and commands.

Materials:

Access to a Unix/Linux terminal environment.

Submission Guidelines:

1. Create a document containing the commands you executed for each


task along with any relevant observations or explanations.

2. Ensure the document is well-organized and clearly presents the results


of each task.

3. Submit the document to your instructor by the specified deadline.

VER. 2024
Objective:

The objective of this lab assignment is to familiarize students with essential Unix
commands for managing time, system information, user accounts, and basic
calculations.

Prerequisites:

Basic understanding of Unix/Linux terminal navigation and commands.

Materials:

Access to a Unix/Linux terminal environment.

VER. 2024
Title: General purpose Utilities Unix Commands (Topic 1)
Cal, Date, Echo, Bc, Passwd, Who, Uname, tty

Definition and usage of the commands :

Cal Command:

Definition: cal is a command-line utility in Unix and Unix-like operating systems that
displays a simple calendar.

Usage: It is used to view the calendar of the current month or any specified month
and year.

Date Command:

Definition: date is a command-line utility in Unix and Unix-like operating systems that
displays the system date and time.

Usage: It is used to view and modify the current date and time, as well as to format
the output according to specified formats.

Echo Command:

Definition: echo is a command-line utility in Unix and Unix-like operating systems that
displays a line of text/string passed as an argument.

Usage: It is used to print messages or values to the terminal, typically used in shell
scripts or to display variable values.

Bc Command:

Definition: bc is a command-line calculator utility in Unix and Unix-like operating


systems.

Usage: It is used for arbitrary precision arithmetic of integers, floating-point numbers,


and mathematical expressions. It provides a command-line interface for calculations.

Passwd Command:

Definition: passwd is a command-line utility in Unix and Unix-like operating systems


that is used to change a user's password.

Usage: It allows users to change their passwords securely by prompting for the
current password and then the new password, enforcing password complexity rules.

VER. 2024
Who Command:

Definition: who is a command-line utility in Unix and Unix-like operating systems that
displays information about users who are currently logged in.

Usage: It shows a list of users currently logged in, along with information such as
their username, terminal, login time, and remote host.

Uname Command:

uname is a Unix command used to display system information about the operating
system. It can provide details such as the system's kernel name, network node
hostname, kernel release, kernel version, machine hardware architecture, and more.

Tty Command:

tty is a Unix command used to display the file name of the terminal connected to
standard input. It is commonly used to determine the terminal device associated with
the current session, which can be useful in scripting and automation.

VER. 2024
Assignment 1

Cal Command:

Open a Unix terminal.

Type cal and press Enter.

Observe the current month's calendar displayed.

Experiment with additional options such as cal -3 to display the previous,


current, and next month's calendars.

Date Command:

Type date and press Enter.

Note down the current date and time displayed.

Experiment with formatting options like date "+%A, %B %d, %Y - %r" to


display the date and time in a customized format.

Echo Command:

Type echo "Hello, World!" and press Enter.

Note the output.

Experiment with variables like echo "The current user is $USER" to display
the current username.

Bc Command:

Type bc and press Enter to enter the bc calculator.

Perform basic arithmetic operations like addition, subtraction, multiplication,


and division.

Experiment with more complex expressions like square roots and


exponentiation.

VER. 2024
Passwd Command:

Type passwd and press Enter.

Follow the prompts to change your password.

Note the password complexity rules enforced.

Who Command:

Type who and press Enter.

Observe the list of users currently logged in.

Experiment with additional options like who -a to display all information.

Uname Command:

Type uname and press Enter.

Note down the system's kernel name.

Experiment with additional options like uname -a to display more detailed


system information.

Tty Command:

Type tty and press Enter.

Note down the terminal device name associated with your session.

Experiment with additional options like tty -s to suppress output if the standard
input is a terminal.

VER. 2024
Title: File System and Handling Ordinary Files (Topic 2)
Mkdir, pwd, rmdir, cp, mv, cd, absolute / Relative pathnames

Definitions for each of the Unix commands :

1. mkdir Command:

- `mkdir` stands for "make directory". It is a Unix command used to create new
directories (folders) within the filesystem. Syntax: `mkdir [directory_name]`.

2. cat Command:

- `cat` stands for "concatenate". It is a Unix command used to display the contents
of one or more files to the terminal. It is also used to concatenate files together and
create new files. Syntax: `cat [file1] [file2] ...`.

3. pwd Command:

- `pwd` stands for "print working directory". It is a Unix command used to display
the current working directory (the directory the user is currently in) in the terminal.

4. rmdir Command:

- `rmdir` stands for "remove directory". It is a Unix command used to delete empty
directories from the filesystem. Syntax: `rmdir [directory_name]`.

5. cp Command:

- `cp` stands for "copy". It is a Unix command used to copy files and directories
from one location to another. Syntax: `cp [source] [destination]`.

6. mv Command:

- `mv` stands for "move". It is a Unix command used to move files and directories
from one location to another. It can also be used to rename files and directories.
Syntax: `mv [source] [destination]`.

VER. 2024
7. cd Command:

- `cd` stands for "change directory". It is a Unix command used to change the
current working directory to a specified directory. Syntax: `cd [directory_path]`.

8. Absolute Pathname:

- An absolute pathname in Unix specifies the complete path from the root directory
("/") to a specific file or directory. It always starts with the root directory and includes
all intermediate directories. For example: `/home/user/documents/file.txt`.

9. Relative Pathname:

- A relative pathname in Unix specifies the path to a file or directory relative to the
current working directory. It does not start with the root directory ("/"). Instead, it
describes the path in relation to the current location. For example:
`../parent_directory/file.txt` or `subdirectory/file.txt`.

Assignment 2

Objective:

The objective of this lab assignment is to familiarize students with basic Unix commands for
directory manipulation and file operations, along with understanding relative pathnames.

mkdir Command:

Open a Unix terminal.

Use the mkdir command to create a new directory named "lab_assignment" in your
current working directory.

Verify that the directory has been created by listing the contents of the current
directory using the ls command.

VER. 2024
cat Command:

Create a new text file named "sample.txt" using any text editor or touch command.

Use the cat command to display the contents of the "sample.txt" file in the terminal.

Experiment with displaying the contents of multiple files using the cat command.

cd Command:

Use the cd command to change your current working directory to the


"lab_assignment" directory created earlier.

Verify that you are now in the "lab_assignment" directory by using the pwd command
to print the current working directory.

pwd Command:

Use the pwd command to display the current working directory.

Discuss with your lab partner the significance of knowing the current working
directory in Unix/Linux systems.

mv Command:

Create a new directory named "backup" inside the "lab_assignment" directory.

Use the mv command to move the "sample.txt" file into the "backup" directory.

Verify that the file has been moved successfully by listing the contents of the
"backup" directory.

rmdir Command:

Use the rmdir command to remove the "backup" directory.

Note that the directory must be empty for the rmdir command to work.

VER. 2024
Experiment with removing non-empty directories using the -r (recursive) option with
rm.

cp Command:

Use the cp command to create a copy of the "sample.txt" file named


"sample_copy.txt" within the "lab_assignment" directory.

Verify that the copy has been created successfully by listing the contents of the
"lab_assignment" directory.

Relative Pathname:

Discuss with your lab partner the concept of relative pathname.

Experiment with using relative pathnames to reference files and directories within the
current directory and its subdirectories.

VER. 2024
Title: File System and Handling Ordinary Files (Topic 3)
wc, ls , cmp, comm, diff, tar

Definitions for each of the Unix commands :

wc Command:

wc stands for "word count." It is a Unix command used to display the number of
lines, words, and bytes contained in a file. It can also be used to count characters in
a file.

ls Command:

ls stands for "list." It is a Unix command used to list the contents of a directory. By
default, it displays the names of files and subdirectories in the specified directory.

cmp Command:

cmp is a Unix command used to compare two files byte by byte. It compares the
contents of two files and reports the first byte where they differ, or it indicates that the
files are identical.

comm Command:

comm is a Unix command used to compare two sorted files line by line. It displays
lines that are unique to each file and lines that are common to both files. It is often
used in conjunction with the sort command.

diff Command:

diff stands for "difference." It is a Unix command used to compare the contents of
two text files line by line. It displays the lines that differ between the two files, along
with specific details about those differences.

tar Command:

tar stands for "tape archive." It is a Unix command used to create and manipulate tar
archives, which are collections of files packaged together into a single file. It is
commonly used for data backup and distribution.

VER. 2024
Assignment 3

ls Command:

Open a Unix terminal.

Use the ls command to list the contents of the current directory.

Experiment with different options such as -l (long format), -a (including hidden files),
and -t (sorted by modification time).

wc Command:

Create a text file named "sample.txt" using a text editor.

Type some text into the "sample.txt" file.

Use the wc command to count the number of lines, words, and characters in the
"sample.txt" file.

Experiment with additional options such as -l (count lines only), -w (count words
only), and -c (count characters only).

cmp Command:

Create two text files named "file1.txt" and "file2.txt" with different contents.

Use the cmp command to compare the contents of the two files byte by byte.

Observe the output to identify differences between the files, if any.

comm Command:

Create two sorted text files named "sorted1.txt" and "sorted2.txt" with some common
and unique lines.

Use the comm command to compare the contents of the two sorted files.

Observe the output to identify lines unique to each file and lines common to both
files.

VER. 2024
diff Command:

Create two text files named "text1.txt" and "text2.txt" with different contents.

Use the diff command to compare the contents of the two files line by line.

Observe the output to identify the lines that differ between the files, along with
specific details about those differences.

Tar command :

Creating a Tar Archive:

Use the tar command to create a tar archive named backup.tar containing all files
within the directory ~/Documents.

Ensure the archive is created in the directory ~/Backups.

Viewing Contents of a Tar Archive:

Use the tar command to list the contents of the backup.tar archive.

Extracting Files from a Tar Archive:

Extract the contents of backup.tar to a directory named restored_files within your


home directory.

Adding Files to an Existing Tar Archive:

Create a new file named notes.txt in your home directory.

Use the tar command to add notes.txt to the backup.tar archive.

Removing Files from a Tar Archive:

Remove the file notes.txt from the backup.tar archive.

VER. 2024
Title: Basic File Attributes and Basic of Shell (Topic 4)
ls options, file permission, chmod, pipes, tee, shell variables

ls Options:

ls is a command used to list files and directories in Unix.

Common options include:

-l: Long format, displaying detailed information about each file.

-a: Include hidden files (those starting with a dot .).

-h: Human-readable file sizes (e.g., KB, MB, GB).

-t: Sort files by modification time.

-r: Reverse the order of sorting.

-R: Recursively list subdirectories.

-F: Append indicator characters to entries (e.g., / for directories, * for executables).

File Permissions:

In Unix-like operating systems, each file and directory has three types of
permissions: read, write, and execute.

Permissions are defined for three categories of users: owner, group, and others.

Permissions can be represented symbolically (e.g., rwxr-xr--) or numerically (e.g.,


755).

r (read): Allows reading or viewing a file or directory.

w (write): Allows modifying or deleting a file or directory.

x (execute): Allows executing a file (for directories, it allows accessing its contents).

VER. 2024
chmod Command:

chmod is used to change the permissions of a file or directory in Unix.

It can be used with symbolic notation (e.g., chmod u+x file.txt) or numeric notation
(e.g., chmod 755 file.txt).

Pipes (|):

Pipes are used to redirect the output of one command as input to another command.

For example, command1 | command2 will pass the output of command1 as input to
command2.

tee Command:

tee reads from standard input and writes to standard output and files simultaneously.

It allows you to see the output on the screen while simultaneously saving it to a file.

Example: command | tee output.txt will display the output of command on the screen
and also save it to output.txt.

Shell Variables:

Shell variables are used to store data or values for later use in Unix shell scripts or
commands.

They can be set using the = operator (e.g., variable_name=value).

To access the value of a variable, you prepend the variable name with a dollar sign
($).

Example: name="John" sets the variable name to "John", and $name retrieves its
value.

VER. 2024
Assignment 4

Using ls Options:

Use the ls command with the following options to explore the contents of your home
directory:

-l: Display detailed information about files and directories.

-a: List all files, including hidden ones.

-h: Show file sizes in a human-readable format.

-t: Sort files by modification time.

-r: Reverse the order of sorting.

Understanding File Permissions:

Use the ls -l command to list files and directories in your home directory along with
their permissions.

Identify the permissions of a few files and directories, and explain what each
permission (r, w, x) signifies for the owner, group, and others.

Changing File Permissions with chmod:

Create a new text file named test.txt.

Use ls -l to verify the initial permissions of test.txt.

Change the permissions of test.txt to allow read, write, and execute for the owner,
and read-only for others using chmod.

Verify the updated permissions using ls -l.

VER. 2024
Understanding Pipes (|):

Execute the ls -l /usr/bin command and observe the output.

Use a pipe to filter the output of ls -l /usr/bin and display only the lines containing the
word "zip".

Using tee Command:

Execute the command ls -l /usr/bin | tee output.txt.

Open output.txt and observe the contents.

Explain the purpose of tee and how it differs from using redirection (>).

Working with Shell Variables:

Set a shell variable named GREETING with the value "Hello, World!".

Print the value of the GREETING variable using echo.

Update the value of GREETING to "Welcome!" and print it again to verify the
change.

VER. 2024
Title: vi Editor (Topic 5)
Vi editor and its modes

VI Editor in Unix:

The VI editor is a powerful text editor available in Unix-like operating systems, such
as Linux. It is renowned for its versatility and efficiency in editing text files directly
from the command line. VI stands for "Visual Editor." VI operates in different modes,
each offering distinct functionality for editing and navigating through text files.

Modes of VI Editor:

Command Mode:

Upon launching VI, it typically opens in Command Mode.

In this mode, keystrokes are interpreted as commands for navigating the file, making
edits, or executing various operations.

You can move the cursor, search for text, copy, cut, paste, delete, and perform other
file manipulation tasks using commands.

To enter Command Mode from other modes, press the Esc key.

Insert Mode:

In Insert Mode, you can insert and edit text directly into the file.

Pressing certain keys (e.g., i, a, o, A, I) switches VI to Insert Mode, allowing text


entry at the cursor position or on a new line.

When in Insert Mode, VI behaves more like a conventional text editor, allowing you
to type and edit text freely.

VER. 2024
To return to Command Mode from Insert Mode, press the Esc key.

Visual Mode:

Visual Mode is used for selecting blocks of text for copying, cutting, or other
operations.

You can enter Visual Mode by pressing v in Command Mode.

Once in Visual Mode, you can move the cursor to select text. Selected text will be
highlighted.

After selecting text, you can perform operations on the selected block, such as
copying (y), cutting (d), or replacing (r).

Assignment 5
Objective:

The objective of this lab assignment is to introduce you to the VI editor and its
functions, including navigation, text manipulation, and saving changes.

Tasks:

Open a File in VI:

Launch the VI editor and open a text file named example.txt located in your home
directory.

Navigation:

Use the arrow keys to move the cursor within the file.

Experiment with basic navigation commands:

h: Move the cursor left.

j: Move the cursor down.

k: Move the cursor up.

l: Move the cursor right.

Practice navigating to different parts of the file.

Switching Modes:

VER. 2024
Practice switching between Command Mode and Insert Mode:

Enter Insert Mode by pressing i.

Type some text at the current cursor position.

Return to Command Mode by pressing Esc.

Text Manipulation:

Use Command Mode to perform basic text manipulation tasks:

Delete the current character under the cursor: x.

Delete the current line: dd.

Copy the current line: yy.

Paste the copied line below the current line: p.

Experiment with these commands to edit the text within the file.

Searching:

Practice searching for text within the file:

Enter Command Mode.

Press / followed by the text you want to search for (e.g., /example).

Press Enter to search forward for the text.

Press n to find the next occurrence of the text.

Saving Changes and Exiting:

Save changes made to the file and exit VI:

Enter Command Mode if not already in it.

Save changes and exit by typing :wq and pressing Enter.

If you wish to exit without saving changes, type :q! and press Enter.

VER. 2024
Title: The Process (Topic 6)
ps with options, internal and external commands, background jobs, kill, nice, at,
batch, cron, time commands in unix

ps Command with Options:

ps command is used to display information about currently running processes.

Common options include:

-e: Display information about all processes.

-f: Full-format listing, showing additional details.

-u user: Display processes for a specific user.

-aux: Display a detailed list of all processes running on the system, including those
by other users.

-p pid: Display information about a specific process ID (PID).

Internal and External Commands:

Internal commands are built-in functions of the shell (e.g., cd, echo, pwd).

External commands are standalone executable programs stored in the system's


directories (e.g., ls, grep, cat).

Internal commands are executed within the shell process, while external commands
are executed as separate processes.

Background Jobs:

Background jobs are processes that run independently of the current shell session.

They can be started with the & symbol appended to the command (e.g., command
&).

Background jobs do not block the shell prompt, allowing the user to continue
executing commands.

VER. 2024
kill Command:

kill command is used to terminate processes in Unix.

It sends a signal to the specified process, instructing it to terminate.

Commonly used signals include:

SIGTERM (default): Gracefully terminate the process.

SIGKILL: Forcefully terminate the process.

Syntax: kill [signal] PID.

nice Command:

nice command is used to modify the priority of a process.

It allows users to adjust the scheduling priority of processes, giving them more or
less CPU time.

Syntax: nice [options] command.

at Command:

at command is used to schedule one-time tasks to be executed at a specified time.

It allows users to specify a particular time for a command or script to be executed.

Syntax: at time [options].

batch Command:

batch command is similar to at, but it executes commands when system load levels
permit.

It schedules commands to be executed when the system load average drops below
a specified value.

Syntax: batch [options].

VER. 2024
cron Command:

cron is a daemon used to execute scheduled tasks at predefined intervals.

It reads scheduled tasks from configuration files called crontabs and executes them
accordingly.

Users can define tasks to be executed hourly, daily, weekly, or at any custom
interval.

Crontab files can be edited using the crontab command.

time Command:

time command is used to measure the execution time of a command or script.

It displays the real, user, and system time taken by the command.

Syntax: time [options] command.

Assignment 6

Objective:

The objective of this lab assignment is to gain practical experience with various Unix
commands, including ps with options, internal and external commands, background
jobs, kill, nice, at, batch, cron, and time.

Using ps Command with Options:

Use the ps command with the following options to display information about
processes:

-e: Display information about all processes.

-f: Display a full-format listing with additional details.

-u username: Display processes for a specific user.

-aux: Display a detailed list of all processes, including those by other users.

VER. 2024
-p pid: Display information about a specific process ID (PID).

Identifying Internal and External Commands:

Identify and list five internal commands of the shell.

Identify and list five external commands available in the system.

Executing Background Jobs:

Start a background job by running a command followed by &.

Verify that the background job is running independently of the current shell session.

Use the jobs command to list background jobs.

Using kill Command:

Identify a process ID (PID) using the ps command.

Use the kill command to terminate the identified process.

Verify that the process has been terminated using ps.

Adjusting Process Priority with nice:

Run a CPU-intensive command with its priority adjusted using nice.

Compare the execution time of the command with and without nice.

Record your observations.

Scheduling Tasks with at:

Use the at command to schedule the execution of a command or script at a specific


time.

Verify that the scheduled task has been added successfully.

Wait for the scheduled time and observe the execution of the task.

VER. 2024
Using batch Command:

Schedule a command to be executed with the batch command.

Ensure that the command is executed when the system load average drops below a
specified value.

Monitor the execution of the scheduled task.

Setting up Cron Jobs:

Edit your user's crontab using the crontab -e command.

Schedule a command or script to be executed periodically using cron syntax (e.g.,


hourly, daily).

Verify that the cron job has been added successfully.

Monitor the execution of the scheduled task.

Measuring Command Execution Time with time:

Use the time command to measure the execution time of a long-running command or
script.

Record the real, user, and system time taken by the command.

Compare the execution time with different commands or inputs.

VER. 2024
Title: Simple Filters (Topic 7)
pr, head, tail, cut, paste, sort, uniq , tr commands in unix

pr Command:

The pr command is used to paginate or format files for printing.

It formats text files for printing by adding headers, footers, and line numbers.

Commonly used options include -d for double spacing, -h for specifying header text,
and -l for setting page length.

head Command:

The head command is used to display the first few lines of a file or input stream.

By default, it displays the first 10 lines, but this can be customized using the -n
option.

Example: head -n 5 filename will display the first 5 lines of the file filename.

tail Command:

The tail command is used to display the last few lines of a file or input stream.

By default, it displays the last 10 lines, but this can be customized using the -n
option.

Example: tail -n 5 filename will display the last 5 lines of the file filename.

cut Command:

The cut command is used to extract specific columns or fields from a file or input
stream.

It allows you to specify delimiters and field positions to extract desired portions of
text.

Example: cut -d',' -f1,3 filename will extract the first and third fields from lines
delimited by commas in the file filename.

VER. 2024
paste Command:

The paste command is used to merge lines from multiple files side by side.

It concatenates corresponding lines from each file separated by a delimiter (by


default, a tab).

Example: paste file1.txt file2.txt will merge lines from file1.txt and file2.txt side by
side.

sort Command:

The sort command is used to sort lines of text files or input streams alphabetically or
numerically.

By default, it sorts in ascending order, but this can be customized using options like -
r for reverse order.

Example: sort filename will sort the lines of the file filename alphabetically.

uniq Command:

The uniq command is used to filter adjacent identical lines from sorted text files or
input streams.

It removes duplicate lines, keeping only one instance of each unique line.

Example: uniq filename will remove consecutive duplicate lines from the file
filename.

tr Command:

The tr command in Unix is used for translating or deleting characters. It reads data
from standard input, performs transformation on the characters, and writes the result
to standard output.

VER. 2024
Assignment 7

Objective:

The objective of this lab assignment is to gain practical experience with various Unix
text processing commands, including pr, head, tail, cut, paste, sort, and uniq.

Using pr Command:

Use the pr command to paginate or columnate a text file for printing.

Specify options to control the formatting, such as page size, headers, footers, and
line numbering.

Using head Command:

Use the head command to display the first 10 lines of a text file.

Experiment with different options to display a different number of lines or a specific


number of bytes.

Using tail Command:

Use the tail command to display the last 10 lines of a text file.

Try displaying a different number of lines, such as the last 20 lines.

Using cut Command:

Use the cut command to extract specific columns or character ranges from a text file.

Experiment with extracting different fields from a delimited text file.

Use options to specify the delimiter character and the fields to extract.

VER. 2024
Using paste Command:

Use the paste command to merge lines of text files horizontally.

Merge two or more text files side by side and observe the output.

Using sort Command:

Use the sort command to sort the lines of a text file alphabetically or numerically.

Experiment with different sorting options, such as ignoring case or specifying a


custom delimiter.

Sort a file in reverse order.

Using uniq Command:

Use the uniq command to filter adjacent matching lines from a sorted text file.

Experiment with different options, such as counting the number of occurrences or


displaying only unique lines.

Apply uniq to a file with duplicate lines and observe the output.

VER. 2024
Title: The Unix Environment (Topic 8)
Environment variable, aliases, history, initialisation script commands in unix

Environment Variables:

Environment variables are dynamic named values that affect the way processes
behave and interact with the operating system.

They are key-value pairs used by the operating system to determine various settings
and configurations.

Examples of environment variables include PATH (which defines the directories to


search for executable files), HOME (which specifies the user's home directory), and
LANG (which determines the language and locale settings).

Environment variables can be set, retrieved, and modified by users and programs
using commands like export and unset.

Aliases:

Aliases are shortcuts or alternative names for commands or command sequences in


Unix-like operating systems.

They allow users to create custom abbreviations for frequently used commands or to
modify the behavior of existing commands.

Aliases are typically defined in configuration files such as .bashrc or .bash_profile.

Example: alias ll='ls -l' defines the alias ll to execute the ls -l command whenever ll is
entered in the terminal.

History:

History is a feature in Unix shells that records a list of previously executed


commands by the user.

It allows users to recall and re-execute previous commands without retyping them.

Users can navigate through the command history using arrow keys or specific
commands like history.

VER. 2024
The size of the command history is typically limited by the HISTSIZE environment
variable.

Initialization Script:

An initialization script is a file executed automatically when a Unix shell starts.

It is used to set up the user's environment, define aliases, customize prompt settings,
and perform other initialization tasks.

Common initialization scripts include .bashrc (for Bash), .bash_profile, .profile,


.bash_login, and .zshrc (for Zsh).

Users can customize these scripts to tailor their shell environment to their
preferences and requirements.

Assignment 8

Objective:

The objective of this lab assignment is to gain practical experience with configuring
environment variables, aliases, history management, and initialization scripts in Unix-
like operating systems.

Environment Variables:

Set a new environment variable named MY_VAR with the value "Hello, World!".

Verify that the environment variable is set correctly using the echo command.

Explore existing environment variables using the env command.

Aliases:

Define an alias named ll to execute ls -l whenever ll is entered in the terminal.

Create aliases for frequently used commands such as grep, cat, or cd.

VER. 2024
History Management:

Execute a series of commands in the terminal session.

Use the history command to display the list of previously executed commands.

Recall and re-execute a command from the history using its number.

Initialization Script:

Open the appropriate initialization script for your shell (e.g., .bashrc, .bash_profile,
.zshrc).

Add a new environment variable definition to the initialization script.

Define a new alias in the initialization script.

Save the changes and exit the editor.

Reload the initialization script to apply the changes without logging out.

VER. 2024
Title : Filters using Regular expression (Topic 9)
Grep, egrap, GRE,sed

grep Command:

grep is a command-line utility used for searching text files or input streams for lines
matching a specified pattern.

It stands for "Global Regular Expression Print."

grep uses regular expressions to match patterns in text.

Syntax: grep [options] pattern [file(s)]

Example: grep "hello" file.txt searches for lines containing the word "hello" in the file
file.txt.

egrep Command:

egrep is an extended version of grep that supports extended regular expressions.

It provides more advanced pattern matching capabilities compared to grep.

egrep is also known as grep -E.

Syntax: egrep [options] pattern [file(s)]

Basic Regular Expression (BRE):

Basic Regular Expression (BRE) is a pattern matching language used by utilities like
grep and sed.

BRE supports a limited set of regular expression metacharacters, including ^ (start of


line), $ (end of line), ., [...], and \.

Quantifiers such as *, +, and ? are not supported in BRE.

Example: grep "^hello" file.txt matches lines starting with "hello".

VER. 2024
sed Command:

sed (stream editor) is a powerful text processing tool used for filtering and
transforming text.

It operates on a line-by-line basis, making changes to input text according to


specified rules.

sed is often used for text substitution, deletion, insertion, and more complex text
manipulations.

Syntax: sed [options] 'script' [file(s)]

Example: sed 's/old/new/' file.txt replaces the first occurrence of "old" with "new" on
each line of file.txt.

Assignment 9

Objective:

The objective of this lab assignment is to gain practical experience with searching for
patterns in text files using grep and egrep, and understanding basic regular
expression syntax.

Using grep:

Use the grep command to search for lines containing a specific word in a text file.

Search for occurrences of a word in multiple files simultaneously.

Explore different options such as -i (ignore case), -n (display line numbers), and -r
(recursively search directories).

VER. 2024
Using egrep:

Use the egrep command to search for lines matching a more complex pattern using
extended regular expressions.

Experiment with patterns containing special characters such as +, *, and ?.

Explore the difference between grep and egrep in terms of pattern matching
capabilities.

Basic Regular Expression (BRE) Practice:

Construct basic regular expressions to match specific patterns in text files.

Use ^ and $ to match the beginning and end of a line respectively.

Utilize character classes such as [...] to match specific sets of characters.

Experiment with metacharacters such as . (match any character) and \ (escape


character).

Advanced Regular Expression (ERE) Practice (Optional):

Experiment with extended regular expressions using egrep.

Use quantifiers such as +, *, and ? to match one or more occurrences, zero or more
occurrences, and zero or one occurrence respectively.

Explore other features of extended regular expressions such as alternation (|) and
grouping (...).

VER. 2024
Title : Essential Shell Programming (Topic 10)
Shell script, read, if, test, [], case, expr, while , for

1. Read: The `read` command is used to read input from the user or from a file
descriptor in a shell script.

2. If condition: The `if` statement allows conditional execution of commands based


on the evaluation of a condition. It's often used in conjunction with comparison
operators like `-eq` (equal), `-ne` (not equal), `-gt` (greater than), `-lt` (less than), etc.

3. Test and [ ] to evaluate expression: The `test` command or its equivalent, `[ ]`, is
used to evaluate expressions and perform conditional tests. It can check various
conditions such as file existence, file types, string comparisons, numeric
comparisons, etc.

4. Case: The `case` statement provides a way to evaluate multiple conditions in a


more concise manner than multiple `if` statements. It allows branching based on the
value of a variable.

5. Expr: The `expr` command evaluates expressions and performs operations in


shell scripts. It's often used for arithmetic operations or to manipulate strings.

6. While: The `while` loop executes a block of commands repeatedly as long as a


specified condition is true. It's useful for iterating over a sequence of data or
performing tasks until a certain condition is met.

7.For in: The `for` loop iterates over a list of items and executes a block of
commands for each item in the list. The `in` keyword is used to specify the list of
items.

VER. 2024
These elements provide the building blocks for writing powerful and efficient shell
scripts in Unix-like environments. By combining them with other Unix commands and
utilities, you can automate a wide range of tasks and customize your system's behavior
according to your needs.

Assignment 10
Q1. Unix shell script assignment that utilizes the `read` command to prompt the user
for input and an `if` condition to evaluate the input:

#!/bin/bash

# Simple Unix Script Assignment

# Prompt the user for their age

echo "Welcome! Please enter your age:"

read age

# Check if the input is a number

if [[ $age =~ ^[0-9]+$ ]]; then

# If age is less than 18, print a message

if [ "$age" -lt 18 ]; then

echo "You are a minor."

else

echo "You are an adult."

fi

else

# If input is not a number, print an error message

echo "Invalid input. Please enter a valid age."

fi

VER. 2024
In this script:

- The `echo` command is used to display a prompt asking the user to enter their age.

- The `read` command reads the user's input and stores it in the `age` variable.

- The script then uses an `if` condition to check if the input is a number. This is done using a
regular expression (`^[0-9]+$`) to ensure that the input consists only of digits.

- If the input is a number, another `if` condition checks if the age is less than 18. If it is, the
script prints a message indicating that the user is a minor; otherwise, it prints a message
indicating that the user is an adult.

- If the input is not a number (i.e., the regular expression check fails), the script prints an
error message asking the user to enter a valid age.

Q2.Unix shell script assignment that uses the `test` command and square brackets `[]`
for conditional evaluation:

#!/bin/bash

# Unix Script Assignment with Test Command

# Prompt the user for a file name

echo "Please enter a file name:"

read filename

# Check if the file exists

if [ -e "$filename" ]; then

# Check if the file is a regular file

if [ -f "$filename" ]; then

echo "$filename exists and is a regular file."

# Check if the file is a directory

elif [ -d "$filename" ]; then

echo "$filename exists and is a directory."

else

echo "$filename exists but is neither a regular file nor a directory."

fi

else

VER. 2024
echo "$filename does not exist."

fi

In this script:

- The `echo` command prompts the user to enter a file name.

- The `read` command reads the user's input and stores it in the `filename` variable.

- The script uses square brackets `[]` along with the `test` command to perform various tests
on the file specified by the user.

- `-e "$filename"` checks if the file exists.

- `-f "$filename"` checks if the file is a regular file.

- `-d "$filename"` checks if the file is a directory.

- Depending on the results of these tests, appropriate messages are printed to the user.

Q3. assignment that involves using a `case` statement in a Unix shell script:

#!/bin/bash

# Unix Script Assignment with Switch Case

# Display a menu to the user

echo "Welcome to the Unix Command Menu!"

echo "Please select an option:"

echo "1. Display current date and time"

echo "2. Display calendar for the current month"

echo "3. Display system information"

echo "4. Exit"

VER. 2024
# Read user input

read choice

# Evaluate user's choice using a case statement

case $choice in

1)

# Display current date and time

date

;;

2)

# Display calendar for the current month

cal

;;

3)

# Display system information

uname -a

;;

4)

# Exit the script

echo "Exiting..."

exit 0

;;

*)

# Handle invalid input

echo "Invalid choice. Please enter a number between 1 and 4."

;;

esac

VER. 2024
In this script:

- The `echo` command displays a menu with options to the user.

- The `read` command reads the user's input and stores it in the `choice` variable.

- The script uses a `case` statement to evaluate the value of `choice` and execute the
corresponding block of code.

- Each option corresponds to a different action: displaying the current date and time,
displaying the calendar, displaying system information, or exiting the script.

- If the user enters an invalid choice, a default option is executed to display an error
message.

Q4. shell script assignment that utilizes the `expr` command for arithmetic operations:

#!/bin/bash

# Unix Script Assignment with expr Command

# Prompt the user for two numbers

echo "Please enter the first number:"

read num1

echo "Please enter the second number:"

read num2

# Perform arithmetic operations using expr

sum=$(expr $num1 + $num2)

difference=$(expr $num1 - $num2)

product=$(expr $num1 \* $num2) # Need to escape the * character

quotient=$(expr $num1 / $num2)

remainder=$(expr $num1 % $num2)

VER. 2024
# Display the results

echo "Sum: $sum"

echo "Difference: $difference"

echo "Product: $product"

echo "Quotient: $quotient"

echo "Remainder: $remainder"

In this script:

- The `echo` command prompts the user to enter two numbers.

- The `read` command reads the user's input and stores it in the `num1` and `num2`
variables.

- The script uses the `expr` command to perform arithmetic operations (addition, subtraction,
multiplication, division, and modulus) on the input numbers.

- The results of the arithmetic operations are stored in variables (`sum`, `difference`,
`product`, `quotient`, `remainder`).

- Finally, the script displays the results to the user.

Q5. assignment that utilizes a while loop in a Unix shell script:

#!/bin/bash

# Unix Script Assignment with While Loop

# Prompt the user to enter a number

echo "Please enter a positive integer:"

read number

# Validate user input to ensure it's a positive integer

while ! [[ $number =~ ^[1-9][0-9]*$ ]]; do

echo "Invalid input. Please enter a positive integer:"

read number

done

VER. 2024
# Initialize variables for calculation

factorial=1

counter=1

# Calculate factorial of the input number using a while loop

while [ $counter -le $number ]; do

factorial=$(expr $factorial \* $counter) # Calculate factorial

counter=$(expr $counter + 1) # Increment counter

done

# Display the factorial of the input number

echo "The factorial of $number is: $factorial"

In this script:

- The `echo` command prompts the user to enter a positive integer.

- The `read` command reads the use r's input and stores it in the `number` variable.

- A while loop is used to validate the user input. The loop continues until the input is a
positive integer (i.e., a number greater than zero).

- Once a valid input is provided, another while loop is used to calculate the factorial of the
input number.

- Inside the loop, the factorial is calculated by multiplying the current value of `factorial` by
the current value of `counter`.

- The loop continues until `counter` reaches the value of the input number.

- Finally, the script displays the factorial of the input number.

VER. 2024
Q6. assignment that utilizes a for loop in a Unix shell script:

#!/bin/bash

# Unix Script Assignment with For Loop

# Prompt the user to enter a number

echo "Please enter a positive integer:"

read number

# Validate user input to ensure it's a positive integer

while ! [[ $number =~ ^[1-9][0-9]*$ ]]; do

echo "Invalid input. Please enter a positive integer:"

read number

done

# Calculate the sum of numbers from 1 to the input number using a for loop

sum=0

for (( i=1; i<=$number; i++ )); do

sum=$(expr $sum + $i)

done

# Display the sum

echo "The sum of numbers from 1 to $number is: $sum"

In this script:

- The `echo` command prompts the user to enter a positive integer.

- The `read` command reads the user's input and stores it in the `number` variable.

- A while loop is used to validate the user input. The loop continues until the input is a positive
integer (i.e., a number greater than zero).

- Once a valid input is provided, a for loop is used to calculate the sum of numbers from 1 to
the input number.

- Inside the loop, the value of `i` ranges from 1 to the input number. The sum is calculated by
adding the current value of `i` to the variable `sum`.

- After the loop, the script displays the sum of numbers from 1 to the input number.

VER. 2024
Title : Essential System Administration (Topic 11)

su, at, cron, useradd, usermod, userdel, run levels, df, du, attributes of device files.

1. su:

- **Definition**: "su" stands for "switch user." It is a Unix command that allows a user to
switch to another user account or become another user during a login session. By default, if
no username is specified, it switches to the superuser (root) account.

- **Usage**: `su [username]`

2. at:

- **Definition**: "at" is a Unix command that allows users to schedule a one-time task to be
executed at a specified time in the future. It is useful for scheduling tasks that do not need to
be repeated regularly.

- **Usage**: `at [time]`

3. cron:

- **Definition**: "cron" is a Unix utility for scheduling repetitive tasks to be executed


automatically at fixed intervals. It is used for tasks that need to be performed regularly, such
as system maintenance, backups, and report generation.

- **Usage**: Cron jobs are defined and managed using the crontab command (`crontab -e`
to edit, `crontab -l` to list, `crontab -r` to remove).

4. useradd:

- **Definition**: "useradd" is a Unix command used to create a new user account on the
system. It adds entries to the system files, including `/etc/passwd`, `/etc/shadow`, and
`/etc/group`, and creates the user's home directory if specified.

- **Usage**: `useradd [options] username`

5. usermod:

- **Definition**: "usermod" is a Unix command used to modify user account properties and
settings. It can be used to change attributes such as the user's login shell, home directory,
primary group, and more.

- **Usage**: `usermod [options] username`

VER. 2024
6. userdel:

- **Definition**: "userdel" is a Unix command used to delete a user account from the
system. It removes the user's entry from system files such as `/etc/passwd`, `/etc/shadow`,
and `/etc/group`, along with the user's home directory if specified.

- **Usage**: `userdel [options] username`

7. Run levels:

- **Definition**: Run levels are a concept in Unix-based operating systems that define the
state of the system and which services and processes are running. Different run levels
correspond to different system states, such as single-user mode, multi-user mode with
networking, or system shutdown.

- **Usage**: Run levels are managed by init, systemd, or other system initialization and
management utilities.

8. df:

- **Definition**: "df" stands for "disk free." It is a Unix command used to display information
about the amount of disk space available and used on filesystems mounted in the system.

- **Usage**: `df [options] [filesystem]`

9. du:

- **Definition**: "du" stands for "disk usage." It is a Unix command used to estimate and
display the disk space used by files and directories.

- **Usage**: `du [options] [directory]`

10. Attributes of device files in Unix:

- Device files in Unix have attributes that define their type, permissions, ownership, and
special characteristics. These attributes include:

- **Type**: Character device (c) or block device (b).

- **Permissions**: Similar to regular files, device files have permissions that control read,
write, and execute access.

- **Ownership**: Device files are owned by a user and a group, just like regular files.

- **Major and Minor Numbers**: These numbers uniquely identify the device to the kernel
and are used for device access and management.

- **Special Characteristics**: Device files may have special characteristics such as being
able to buffer or cache data, or being able to communicate with hardware devices.

VER. 2024

You might also like