0% found this document useful (0 votes)
28 views60 pages

Unix24 Lab Manual

The UNIX & Shell Programming Lab Manual outlines the objectives and outcomes for engineering students, focusing on the application of UNIX commands and shell scripting. It includes a comprehensive list of experiments designed to teach various aspects of UNIX, such as file management, user management, and scripting with tools like awk and perl. The manual emphasizes practical skills in using UNIX for problem-solving and system management in an educational context.

Uploaded by

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

Unix24 Lab Manual

The UNIX & Shell Programming Lab Manual outlines the objectives and outcomes for engineering students, focusing on the application of UNIX commands and shell scripting. It includes a comprehensive list of experiments designed to teach various aspects of UNIX, such as file management, user management, and scripting with tools like awk and perl. The manual emphasizes practical skills in using UNIX for problem-solving and system management in an educational context.

Uploaded by

webiga8260
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

UNIX & SHELL PROGRAMMING LAB MANUAL

(II YEAR – I SEMESTER)

(2024-2025)

Prepared by

DR.SHABEENA SAYED
Assistant Professor
IT

[1]
[2]
PROGRAMOUTCOMES(POs)
Engineeringstudentswillbeableto:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering
specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching
substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development ofsolutions: Designsolutions for complex engineeringproblems and designsystemcomponents or
processes that meet the specified needs with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
4. Conduct investigations ofcomplex problems: Useresearch-based knowledgeand research methods including design of
experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools
including prediction and modeling to complex engineering activities with an understanding of the limitations.
6. The engineer and society: Applyreasoning informedbythecontextual knowledgetoassess societal, health, safety, legal and
cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering
practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community and with
society at large, such as, being able to comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-long
learning in the broadest context of technological change.

PROGRAMSPECIFICOUTCOMES
Studentswillbeableto
13.

PSO1:Organize,maintainandprotectITInfrastructuralresources.
PSO2:DesignandDevelopweb,mobile, andsmartappsbasedsoftwaresolutionstothereal

[3]
CONTENTS

Page
S.No ListofExperiments No
TO STUDY INTRODUCTION OF UNIX AND perform THE
1 INSTALLATION of UNIX.

2 Execution of Unix General Purpose Utility Commands like echo, clear, exit, date, 6
time, uptime, cal, cat, tty, man, which, history, id, pwd, whoami, ping, ifconfig, pr,
lp, lpr, lpstat, lpq, lprm, cancel, mail, etc.

3 A. 12
Study of Unix file system (tree structure), file and directory permissions, single and
multiuser environment
B.
Execution of File System Management Commands like ls, cd, pwd, cat, mkdir,
rmdir, rm, cp, mv, chmod, wc, piping and redirection, grep, tr, echo, sort, head, tail,
diff, comm, less, more, file, type, wc, split, cmp, tar, find, vim, gzip, bzip2, unzip,
locate, etc.
4 Execution of User Management Commands like who, whoami, su, sudo, login, 25
logout, exit, passwd, useradd/adduser, usermod, userdel, groupadd, groupmod,
groupdel, gpasswd, chown, chage, chgrp, chfn, etc
5 ToPracticeonprocess,disk,networkutilities
6 To practice Memory Management Commands in UNIX/Linux with description,
syntax, and examples
7 TopracticeUNIXcommandsonViEditor.
8 a) Study of Shell, Types of Shell, Variables andOperators
b) Execute the following Scripts (at least 6):
(i) Write a shell script to perform arithmetic operations.
(ii) Write a shell script to calculate simple interest.
(iii) Write a shell script to determine largest among three integer numbers.
(iv) Write a shell script to determine a given year is leap year or not
(v) Write a shell script to print multiplication table of given number using
while statement.
(vi) Write a shell script to search whether element is present is in the list or
not.
(vii) Write a shell script to compare two strings.
(viii) Write a shell script to read and check if the directory / file exists or not,
if not make the directory / file.
(ix) Write a shell script to implement menu-driven calculator using case
statement.
(x) Write a shell script to print following pattern
*
**
***
**** [5]
Execute following script using grep/sed command
(i) Write a script using grep command to find the number of words character,
9 words and lines in a file.
(ii) Write ascriptusing egrep command to display list of specific type of files
in the directory.
(iii) Write a script using sed command to replace all occurrences of particular
word in given a file.
(iv) Write a script using sedcommand to print duplicated lines in input.

Execute following script using Awk/perl command


10
(i) Write an awk script to print all even numbers in a given range.
(ii) Write an awk script to develop a Fibonacci series (take user input for
number of terms).
(iii) Write a perl script to sort elements of an array.
(iv) Write a perl script to check a number is prime or not.

Assignment 1
11
Assignment2
12
1. TO STUDY INTRODUCTION OF UNIX AND DO THE INSTALLATION.
2. Execution of Unix General Purpose Utility Commands like echo, clear, exit, date, time, uptime, cal, cat, tty, man, which,
history, id, pwd, whoami, ping, ifconfig, pr, lp, lpr, lpstat, lpq, lprm, cancel, mail, etc.

1. echo

The echo command is used to display a line of text/string on the terminal.

Syntax:

echo [options] [string]

Example:

echo Hello, World!

2. clear

The clear command clears the terminal screen.

Syntax:

clear

Example:

clear

3. exit

The exit command is used to exit the current shell or terminal.

Syntax:

exit

Example:

exit

4. date

The date command displays the current date and time.

Syntax:

date [options]

Example:

6
date

5. time

The time command is used to determine how long a command takes to run.

Syntax:

time [command]

Example:

time ls

6. uptime

The uptime command displays how long the system has been running.

Syntax:

uptime

Example:

uptime

7. cal

The cal command displays a calendar.

Syntax:

cal [month] [year]

Example:

cal
cal 12 2025

8. cat

The cat command concatenates and displays files.

Syntax:

cat [file]

Example:

cat file.txt

7
9. tty

The tty command prints the file name of the terminal connected to standard input.

Syntax:

tty

Example:

tty

10. man

The man command displays the manual pages for other commands.

Syntax:

man [command]

Example:

man ls

11. which

The which command locates a command.

Syntax:

which [command]

Example:

which ls

12. history

The history command lists previously executed commands.

Syntax:

history

Example:

history

13. id

The id command prints real and effective user and group IDs.
8
Syntax:

id

Example:

id

14. pwd

The pwd command prints the current working directory.

Syntax:

pwd

Example:

pwd

15. whoami

The whoami command prints the username of the current user.

Syntax:

whoami

Example:

whoami

16. ping

The ping command tests the network connection to a server.

Syntax:

ping [host]

Example:

ping google.com

17. ifconfig

The ifconfig command configures network interfaces.

Syntax:

ifconfig

9
Example:

ifconfig

18. pr

The pr command prepares files for printing.

Syntax:

pr [options] [files]

Example:

pr file.txt

19. lp, lpr

The lp or lpr command submits print jobs.

Syntax:

lp [options] [files]

Example:

lp file.txt

20. lpstat

The lpstat command displays printer status information.

Syntax:

lpstat [options]

Example:

lpstat -p

21. lpq

The lpq command displays print queue status.

Syntax:

lpq [options]

Example:

lpq

10
22. lprm

The lprm command removes print jobs from the print queue.

Syntax:

lprm [job ID]

Example:

lprm 123

23. cancel

The cancel command cancels print jobs.

Syntax:

cancel [job ID]

Example:

cancel 123

24. mail

The mail command sends and receives emails.

Syntax:

mail [options] [recipient]

Example:

mail -s "Subject" [email protected]

11
3.
A.Study of Unix file system (tree structure), file and directory permissions, single and multiuser environment
B.
Execution of File System Management Commands like ls, cd, pwd, cat, mkdir, rmdir, rm, cp, mv, chmod, wc,
piping and redirection, grep, tr, echo, sort, head, tail, diff, comm, less, more, file, type, wc, split, cmp, tar, find,
vim, gzip, bzip2, unzip, locate, etc.

.
Aim:To implement file permissions
Description:
1. Unix File System (Tree Structure)

Unix-like operating systems (such as Linux) organize files and directories in a hierarchical tree structure. This structure
starts from the root directory (/) and branches out into subdirectories and files. Here’s a breakdown:

 Root Directory (/): At the top of the hierarchy, everything starts from here.
 Subdirectories: Directories within directories, forming branches of the tree.
 Files: Actual data or programs stored within directories.

Key Directories in Unix:

12
NAME DESCRIPTION

/ The slash / character alone denotes the root of the filesystem tree.
Unix file
system:
Stands for “binaries” and contains certain fundamental utilities, such
/bin
as ls or cp, which are generally needed by all users.

Contains all the files that are required for successful booting
/boot
process.

Stands for “devices”. Contains file representations of peripheral


/dev
devices and pseudo-devices.

Contains system-wide configuration files and system databases.


/etc Originally also contained “dangerous maintenance utilities” such as
init,but these have typically been moved to /sbin or elsewhere.

/home Contains the home directories for the users.

Contains system libraries, and some critical files such as kernel


/lib
modules or device drivers.

Default mount point for removable devices, such as USB sticks,


/media
media players, etc.

Stands for “mount”. Contains file system mount points. These are
used, for example, if the system uses multiple hard disks or hard
/mnt
disk partitions. It is also often used for remote (network) file
systems, CD-ROM/DVD drives, and so on.

procfs virtual file system showing information about processes as


/proc
files.

The home directory for the super user “root” – that is, the system
administrator. This account’s home directory is usually on the initial
file system, and hence not in /home (which may be a mount point for
another filesystem) in case specific maintenance
/root needs to be performed, during which other filesystems are not
available. Such a
case could occur, for example, if a hard disk drive suffers physical
failures and cannot be
properly mounted.

A place for temporary files. Many systems clear this directory upon
startup; it might
/tmp have tmpfs mounted atop it, in which case its contents do not
survive a reboot, or it
might be explicitly cleared by a startup script at boot time.

Originally the directory


13
holding user home directories,its use has
changed. It
now holds executables, libraries, and shared resources that are not
system critical, l
Directories or Files and their Description

The image provides a classification of the Unix file system, listing the different types of files and components in the Unix
operating system. Here's an explanation of each category:

1. Ordinary Files:

 These are the most common type of files in Unix.


 They store user data and include text files, source code, images, videos, etc.
 Ordinary files can be read, written to, or executed (if they are programs).

2. Directories:

 Directories are special files that contain information about other files and subdirectories.
 They are used to organize the file system in a hierarchical structure.
 Commands like ls and cd are used to interact with directories.

3. Special Files:

 Special files are used to represent hardware devices and provide an interface to them.
 These include:
o Character Device Files: Used for devices that transfer data character by character (e.g., keyboards, serial ports).
o Block Device Files: Used for devices that transfer data in blocks (e.g., hard drives, USB storage).

4. Pipes:

 Pipes are used for inter-process communication.


 They allow data to flow from one process to another in a unidirectional manner.
 Example: ls | grep txt (where the output of ls is sent as input to grep).

14
5. Sockets:

 Sockets provide an interface for network communication between processes, either on the same machine or across different
machines.
 They enable communication using protocols like TCP/IP.
 Example: Web servers and clients use sockets for communication.

6. Symbolic Links:

 Symbolic links (symlinks) are references or shortcuts to other files or directories.


 They allow multiple paths to access the same file or directory.
 Example: If file1 is a symbolic link to file2, any access to file1 will refer to file2.

Summary:

The Unix file system is versatile and supports different file types to handle diverse operations. Each type of file serves a
specific purpose, contributing to Unix's ability to manage data, devices, and processes efficiently.

FilePermissions:
Every file and directory in yourUNIX systemhasfollowing3permissionsdefinedfortheuser, groupandothers.

 Read:This permissiongivesyoutheauthoritytoopenandreada file. Readpermissionona directorygives youthe ability


to lists its content.
 Write:The write permission gives you the authority to modify the contents of a file. The write permission on a
directory gives you the authority to add, remove and rename files stored in the directory.
 Execute:In Unix/Linux,you cannot run a program unless the execute permission is set.If the execute permissionis
not set, you might still be able to see/modify the program code (provided read & write permissions are set), but not
run it.

'chmod'commandwhichstands for 'changemode'can set permissions (read, write, execute) ona file/directoryfor the
owner, group and the world.

Syntax:chmod permissions filename

There are 2 ways to use the command -

1. Absolutemode
2. Symbolicmode

Absolute(Numeric)Mode

Inthismode,filepermissionsarenotrepresentedascharactersbutathree-digitoctalnumber.

15
Output:

16
:
Symbolic Mode In the Absolute mode, you change permissions for all 3 owners. In the symbolic mode, you can modify
permissions of a specific owner. It makes use of mathematical symbols to modify the file permissions.

Operator Description

+ Addsapermissiontoa fileordirectory

- Removesthepermission

= Setsthepermissionandoverridesthe
permissions set earlier.

Thevariousownersarerepresentedas-

UserDenotations
u user/owner
g group
o other
a all

Output:

Command to View Permissions:

Use ls -l command to view permissions. Here's an example output:

$ ls -l
-rw-r--r-- 1 user group 321 Jan 14 10:00 file.txt

 The first column (-rw-r--r--) shows permissions for owner, group, and others respectively.

Command to Change Permissions:

Use chmod command to change permissions. Example:

$ chmod u+x file.txt // Adds execute permission for the owner.


$ chmod go-r file.txt // Removes read permission for group and others.
17
3. Single and Multiuser Environments

Single User Environment:

 Definition: Only one user interacts with the system at a time.


 Advantages: Simplified setup and usage, suitable for personal systems.
 Disadvantages: Limited collaboration and sharing.

In a single-user environment, commands are generally used for system maintenance, configuration, or operations that
don't require multi-user interactions. Here is a list of essential Unix commands for a single-user environment:

File and Directory Management

pwd - Print the current working directory.

$ pwd

ls - List the contents of a directory.

$ ls

cd - Change the current directory.

$ cd /path/to/directory

mkdir - Create a new directory.

$ mkdir new_folder

rmdir - Remove an empty directory.

$ rmdir empty_folder

rm - Remove files or directories.

$ rm file.txt
$ rm -r folder_to_delete

cp - Copy files or directories.

$ cp source_file destination_file
$ cp -r source_directory destination_directory

mv - Move or rename files or directories.

$ mv old_name new_name

File Operations

cat - View the contents of a file.

$ cat file.txt

18
more and less - View files one screen at a time.

$ more file.txt
$ less file.txt

nano or vim - Edit files.

$ nano file.txt
$ vim file.txt

touch - Create an empty file or update the timestamp of an existing file.

$ touch newfile.txt

find - Search for files or directories.

$ find /path -name "filename"

locate - Quickly find files using an indexed database.

$ locate filename

System and Process Monitoring

whoami - Display the current user.

$ whoami

id - Show user ID (UID) and group ID (GID).

$ id

ps - Display active processes.

$ ps

top - Show real-time system resource usage.

$ top

File and Directory Permissions

chmod - Change file or directory permissions.

$ chmod 644 file.txt

chown - Change the owner of a file or directory.

$ chown user:group file.txt

19
Disk Usage and Storage

df - Show disk space usage.

$ df -h

du - Show directory or file size.

$ du -h file.txt

System Management

date - Display or set the system date and time.

$ date

shutdown - Power off or reboot the system.

$ shutdown now

reboot - Reboot the system.

$ reboot

Archiving and Compression

tar - Archive files.

$ tar -cvf archive.tar file1 file2

gzip / gunzip - Compress and decompress files.

$ gzip file.txt
$ gunzip file.txt.gz

Networking

ping - Check connectivity to another host.

$ ping example.com

curl - Fetch content from a URL.

$ curl https://example.com

Miscellaneous

man - Display the manual for any command.

$ man ls

echo - Print messages to the terminal.

20
$ echo "Hello, Unix!"

These commands are ideal for a single-user working on a Unix system for personal use, development, or system
administration.

Multiuser Environment:

 Definition: Multiple users can interact with the system concurrently.


 Advantages: Enables sharing of resources, collaboration, and efficient use of computing resources.
 Disadvantages: Requires robust access control (permissions) to manage security and resource allocation.

In a multi-user environment, Unix-like systems provide several commands to manage users, groups, permissions, and
system resources effectively. Here's a categorized list of essential commands for managing a multi-user environment:

1. User Management Commands

who: Display users currently logged in.

who

w: Show active users and their activities.

whoami: Display the current user's username.

whoami

id: Show user ID (UID), group ID (GID), and group memberships.

id

adduser / useradd: Add a new user to the system.

sudo adduser username


sudo useradd username

deluser / userdel: Remove a user from the system.

sudo deluser username


sudo userdel username

passwd: Change a user's password.

passwd username

21
2. Group Management Commands

groupadd: Create a new group.

sudo groupadd groupname

groupdel: Delete a group.

sudo groupdel groupname

usermod: Modify user details, including adding/removing users to/from groups.

sudo usermod -aG groupname username

groups: Display the groups a user belongs to.

groups username

3. Permissions and Ownership Commands

chmod: Change file/directory permissions.

chmod 755 filename


chmod u+x script.sh

chown: Change ownership of files/directories.

sudo chown user:group filename

umask: Set default permissions for new files and directories.

umask 022

ls -l: List files with detailed permissions.

ls -l /path/to/directory

4. Process and Resource Management Commands

ps: Display information about running processes.

ps aux

top: Interactive process viewer to monitor system resource usage.

top

kill: Terminate a process by its PID.

kill 1234

22
nice / renice: Set or modify process priority.

nice -n 10 command
renice 5 -p 1234

5. System Monitoring Commands

uptime: Show system uptime and load average.

uptime

df: Check disk usage.

df -h

du: Show disk usage for files/directories.

du -sh /path/to/directory

free: Display memory usage.

free -h

6. Networking Commands

netstat: Display network connections, routing tables, and interface statistics.

netstat -tuln

ping: Test connectivity to another host.

ping google.com

ssh: Connect to another machine via SSH.

ssh user@remote_host

scp: Securely copy files between systems.

scp file.txt user@remote_host:/path/to/destination

7. System Logs and Security

last: Show last login information.

last

tail: View the end of a log file (e.g., system logs).

23
tail -f /var/log/syslog

sudo: Execute commands with superuser privileges.

sudo command

Summary of Common Use Cases


Task Command
Check logged-in users who, w
Add/remove users or groups useradd, userdel, groupadd, groupdel
Change file permissions chmod, chown
Monitor system resources top, free, df
Manage processes ps, kill, nice
View and manage logs last, tail

Summary

Understanding Unix file systems, permissions, and environments is crucial for effective system administration and
usage. By grasping these concepts, you can navigate and manage Unix-based systems proficiently, whether in single-
user or multiuser setups. Practice using commands like ls, chmod, and exploring the file tree (/) to reinforce your
understanding.

24
4.Execution of User Management Commands like who, whoami, su, sudo, login, logout, exit, passwd,
useradd/adduser, usermod, userdel, groupadd, groupmod, groupdel, gpasswd, chown, chage, chgrp, chfn, etc

Description:

1. who

Description: Displays a list of users currently logged into the system.


Syntax: who [options]
Example:

who

Output:

user1 tty1 Jan 08 08:15


user2 pts/0 Jan 08 09:02

2. whoami

Description: Displays the current logged-in user's username.


Syntax: whoami
Example:

whoami

Output:

user1

3. su

Description: Switches to another user account.


Syntax: su [username]
Example:

su admin

After entering the password, the shell switches to the admin user.

25
4. sudo

Description: Executes commands as another user, typically root.


Syntax: sudo [command]
Example:

sudo apt update

Executes the apt update command with root privileges.

5. login

Description: Logs into a system or user account. Typically used in terminals.


Syntax: login [username]
Example:

login user1

Prompts for the user's password and logs into the account.

6. logout

Description: Logs out from the current session.


Syntax: logout
Example:

logout

7. exit

Description: Exits the current shell or session.


Syntax: exit [n]
Example:

exit

If you pass a numeric value n, it returns that as the exit status.

8. passwd

Description: Changes a user's password.


Syntax: passwd [username]
Example:
26
passwd

Prompts the user to enter a new password.

9. useradd/adduser

Description: Adds a new user to the system.


Syntax:

 useradd [options] username


 adduser [username] (Debian-based systems)

Example:

useradd -m -s /bin/bash newuser

Adds a user newuser with a home directory and bash shell.

10. usermod

Description: Modifies an existing user's account details.


Syntax: usermod [options] username
Example:

usermod -l newusername oldusername

Renames oldusername to newusername.

11. userdel

Description: Deletes a user account.


Syntax: userdel [options] username
Example:

userdel -r username

Deletes the user and their home directory.

27
12. groupadd

Description: Adds a new group.


Syntax: groupadd [options] groupname
Example:

groupadd developers

Adds a group named developers.

13. groupmod

Description: Modifies an existing group.


Syntax: groupmod [options] groupname
Example:

groupmod -n newgroupname oldgroupname

Renames oldgroupname to newgroupname.

14. groupdel

Description: Deletes a group.


Syntax: groupdel groupname
Example:

groupdel developers

15. gpasswd

Description: Administers /etc/group to set or update group passwords.


Syntax: gpasswd [options] groupname
Example:

gpasswd developers

Prompts to set a password for the developers group.

16. chown

Description: Changes ownership of a file/directory.


Syntax: chown [owner][:[group]] file
Example:
28
chown user1:developers file.txt

Sets user1 as the owner and developers as the group for file.txt.

17. chage

Description: Changes user account expiration details.


Syntax: chage [options] username
Example:

chage -l username

Displays password aging details for the user.

18. chgrp

Description: Changes the group ownership of a file/directory.


Syntax: chgrp groupname file
Example:

chgrp developers file.txt

Changes the group of file.txt to developers.

19. chfn

Description: Changes a user's full name and other information.


Syntax: chfn [options] username
Example:

chfn username

Prompts the user to update personal details like full name and phone number.

Notes:

 Root Privileges: Many of these commands require root or sudo privileges.


 Best Practices: Always confirm critical changes (like deleting users) to avoid system issues.

29
5.To Practice on process,disk,networkutilities
Process utilities:
An instance of a program is calleda Process. In simple terms, any command that you give to your unix machine
starts a new process.
ps:
 ps(Processstatus) canbeusedtosee/listalltherunningprocesses.
 For more information-f(full) canbe usedalongwith ps
 For a singleprocess information,ps along with process id is used

kill:
Wheninvokedkillcommand sends a termination signal to theprocess being killed. Wecanemploysurekill signal to
forcibly terminate a process. Signal number for sure kill is 9
$kill Pid:

30
DiskUtilities:
du:(Diskusuage)
du command-lineutilityhelpsyoutofindoutthediskusageofset offilesoradirectory.
Syntax:du[OPTION]...[FILE]…

31
df:(Diskfreespace)
dfcommand displaystheamountofdiskspaceavailableonthefilesystemcontainingeachfilenameargument.
Syntax:df[OPTION]...[FILE]...

NetworkUtilities:
1. ifconfig:Itisusedtoconfigurenetworkinterfaceparameters.

2. w:

32
wprintsa summaryofthecurrentactivityonthesystem, includingwhateachuserisdoing, andtheirprocesses.

33
34
5.

6. TO PRACTICE Memory Management Commands in UNIX/Linux with description, syntax, and examples.

1. free

Description: Displays the total, used, and available memory (RAM and swap) on the system.
Syntax: free [options]
Example:

free -h

Output: Displays memory information in human-readable format.

2. /proc/meminfo

Description: A file that provides detailed information about memory usage from the system's perspective.
Syntax: cat /proc/meminfo
Example:

cat /proc/meminfo

Output: Displays details like total memory, free memory, buffers, cached memory, etc.

3. top

Description: Provides a dynamic real-time view of system processes, including memory and CPU usage.
Syntax: top
Example:

top

Press M in the top interface to sort processes by memory usage.

4. htop

Description: An enhanced, user-friendly version of top with an interactive UI.


Syntax: htop
Example:

htop

35
Use arrow keys to navigate and F keys for actions (e.g., killing a process).

5. df

Description: Reports file system disk space usage.


Syntax: df [options] [file]
Example:

df -h

Output: Displays disk space usage in a human-readable format for all mounted filesystems.

6. du

Description: Estimates and displays file or directory disk usage.


Syntax: du [options] [directory/file]
Example:

du -sh /var/log

Output: Shows the size of the /var/log directory in human-readable format.

7. vmstat

Description: Reports system performance, including memory, CPU, and IO statistics.


Syntax: vmstat [options] [delay [count]]
Example:

vmstat 2 5

Displays system performance statistics every 2 seconds, 5 times.

8. dmidecode

Description: Displays detailed hardware information, including memory details, by decoding the DMI table.
Syntax: dmidecode [options]
Example:

sudo dmidecode -t memory

Output: Shows detailed information about the system's memory modules.

36
9. sar

Description: Collects, reports, and saves system activity, including memory usage.
Syntax: sar [options]
Example:

sar -r 2 5

Reports memory usage statistics every 2 seconds for 5 iterations.

10. pagesize

Description: Displays the size of a memory page in bytes.


Syntax: pagesize
Example:

pagesize

Output: Returns the memory page size, typically 4096 bytes on most systems.

Examples with Common Use Cases

1. Check Available Memory:


2. free -m

Displays memory in MB.

3. Monitor Real-Time Processes and Memory Usage:


4. top

Press M to sort by memory.

5. Analyze Disk Usage of a Directory:


6. du -h --max-depth=1 /home

Lists sizes of all subdirectories in /home.

7. Get Swap Usage with sar:


8. sar -S 2 5

Reports swap space usage every 2 seconds for 5 iterations.

9. View Detailed Memory Hardware Information:


10. sudo dmidecode -t memory

37
Tips for Memory Management

 Use htop for interactive monitoring.


 Automate system monitoring with sar or write scripts using /proc/meminfo.
 For hardware upgrades, use dmidecode to identify memory specifications.
 Regularly check and clean up unnecessary files using du and df.

38
7.TopracticeUNIXcommandsonViEditor.

Vi Editor:The default editor that comes with the UNIX operating system is called vi (visual editor). Using vi editor,
wecan edit an existing file or createa new file. Wecan also use this editor to just read a text file.
Syntax:vifilename
$vipraneetha1

ToworkonVIeditor,youneedtounderstand itsoperationmodes.Theycanbedividedintotwomainparts.

1. Commandmode:
Thevieditor opensinthismode,anditonlyunderstands commands

 Inthismode, youcan,movethecursorandcut, copy,pastethetext


 Thismodealsosavesthechangesyouhavemadetothefile
 Commandsarecasesensitive.Youshouldusetheright lettercase.

2. Insertmode:

 Thismodeisfor insertingtextinthefile.

 YoucanswitchtotheInsertmodefromthecommandmode bypressing'i' onthekeyboard

 OnceyouareinInsert mode,anykey wouldbetakenasaninput forthefileonwhichyouarecurrently working.

 ToreturntothecommandmodeandsavethechangesyouhavemadeyouneedtopresstheEsckey

39
viEditingcommands:

Note:Youshould be inthe"command mode"to executethesecommands.VIeditoriscase-sensitiveso make sure you type


the commands in the right letter-case.

ToExitvi:

:x<Return> quitvi,writingout modifiedfiletofilenamed in original invocation


:wq<Return> quitvi,writingout modifiedfiletofilenamedinoriginal invocation
:q<Return> quit (orexit) vi

InsertingorAddingText:

Inserttextbeforecursor, until<Esc>hit
inserttextatbeginningofcurrentline, until <Esc>hit
appendtextaftercursor,until<Esc>hit
appendtextto endofcurrent line,until<Esc>hit
openandputtextinanewlinebelowcurrentline,until<Esc>hit
openandputtextinanewline above currentline,until<Esc>hit

ChangingText:

replacesinglecharacterundercursor(no<Esc>needed)
replacecharacters, startingwithcurrentcursorposition, until <Esc>hit
changethecurrentwordwithnewtext,
cw
startingwiththecharacterundercursor, until<Esc>hit
change(replace) thecharactersinthecurrentline,until<Esc>hit
cc change(replace)theentirecurrentline, stoppingwhen<Esc>ishit

DeletingText:

deletesinglecharacterunder cursor

40
dw deletethesinglewordbeginningwithcharacterundercursor
D deletetheremainderoftheline,startingwithcurrentcursorposition
dd irecurrentline

Output:

Practiceremainingcommandsinexperiment1onvieditor

41
6.
6
6.
8.
a) Study of Shell, Types of Shell, Variables andOperators
b) Execute the following Scripts (at least 6):
(i) Write a shell script to perform arithmetic operations.
(ii) Write a shell script to calculate simple interest.
(iii) Write a shell script to determine largest among three integer numbers.
(iv) Write a shell script to determine a given year is leap year or not
(v) Write a shell script to print multiplication table of given number using while statement.
(vi) Write a shell script to search whether element is present is in the list or not.
(vii) Write a shell script to compare two strings.
(viii) Write a shell script to read and check if the directory / file exists or not, if not make the directory / file.
(ix) Write a shell script to implement menu-driven calculator using case statement.
(x) Write a shell script to print following pattern:

*
**
***
****
(xi) Write a shell script to perform operations on directory like: display name of current directory; display list of directory
contents; create another directory, write contents on that and copy it to a suitable location in your home directory; etc.
7. Execute the following scripts using grep / sed commands:
(i) Write a script using grep command to find the number of words character, words and lines in a file.
(ii) Write ascriptusing egrep command to display list of specific type of files in the directory.
(iii) Write a script using sed command to replace all occurrences of particular word in given a file.
(iv) Write a script using sedcommand to print duplicated lines in input.
8.
Execute the following scripts using awk / perl languages:
(i) Write an awk script to print all even numbers in a given range.
(ii) Write an awk script to develop a Fibonacci series (take user input for number of terms).
(iii) Write a perl script to sort elements of an array.
(iv) Write a perl script to check a number is prime or no

Aim:Toprintthefactorialoffirstnnaturalnumbers.
Program:
echo"enterrange"
read n
i=1
while[$i-le$n] do
j=1 fact=1
while[$j-le$i] do
fact=`expr$fact\*$j` j=`expr
$j + 1`
done
echo factorialof$iis:$fact
42
i=`expr $i + 1`
done

Output:

43
2. Writeashellscriptto generateamultiplicationtableofthegivennumber.
Aim:To generate a multiplication table of the given number.
Description:
To display any information on the screen we can use ‘echo‘ command . The text within the double quoteswas
displayed on the screen. ‘expr’ command is used to evaluate the expression. The expression within the symbol
‘ ‘ is evaluated byusing the expr command $variable gives the value ofthe variable it contained expr command
combines two functions perfumes arithmetic operations on integers manipulate strings
Theoperand+,-,*etc..,mustbe enclosedoneither sidebywhite space.

Program:
echo"whichnumbertogeneratemultiplicationtable"
read number
i=1
while[$i-le10] do
echo "$number*$i=`expr$number \*$i`"
i=`expr $i + 1`
done
Output:

44
3. Writeashellscript thatcountsthenumberoflinesandwordspresentinagiven file.
Aim:Tocountsthenumber oflinesandwordspresentinagiven file.
Description:wccommand isusedto displaythenumberofcharacters, words,lines inagivenfile. “|” inputs the
output of file content to wc.
Program:
echoEnterthefilename
read file
w=`cat$file|wc-w`
c=`cat $file | wc -c`
l=`cat $file | wc -l`
echoNumberofcharactersin$fileis$c
echo Number of words in $file is $w
echo Number of lines in $file is $l

45
4. Writeashellscriptthatdisplaysthelistofallfiles inthegivendirectory.
Aim:Todisplaythelistofallfilesinthegiven directory
Program:
echodirectory
read d
forfilein$d
do
if[-d$file]
then
ls$file
fidone

46
5. Write a shell script (small calculator)that adds, subtracts, multiplies and divides the given two integers.
Therearetwodivisionoptions:onereturnsthequotient andtheotherreturnsreminder.Thescriptrequires3
arguments: The operation to be used and two integer numbers. The options are add (-a), subtract (-s),
multiply (-m), quotient (-c) and reminder (-r).

Program:

echo"enterfirstvalue"
read x
echo"EnterSecondValue" read
y
while[${q:-1}-ne0] do
echo "Enter -a for adding"
echo"Enter-sforsubtraction"
echo"Enter-mformultiplication" echo
"Enter -c for Quotient"
echo"Enter-rforreminder"
echo choice
read b
case$bin
-a)p=`expr$x+$y`
echo "Sum = $p"
;;
-s)p=`expr $x - $y`
echo"difference=$p"

;;
-m)p=`expr$x\*$y`
echo "Product = $p"
;;
-c)p=`expr $x/ $y`
echo "quotient=$p"
;;
-r)p=`expr$x%$y`
echo "reminder=$p"
;;
*)echo"none"br
eak

47
;;
esac
done

Output:

48
6. Writeaprogramthattakesoneormore file/directorynamesascommand line input andreportsthefollowing
information on the file: File type, Number of links, Time of last access, Read, Write and Execute
permissions.

Program:
#include<stdio.h>
#include<unistd.h>
#include<dirent.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<time.h>
intmain(intargc,char *argv[])
{
char *at,*mt,*ct;
struct stat buf;
stat(argv[1],&buf);
printf("theinodenois:%ld\n",buf.st_ino);
if(S_ISDIR(buf.st_mode))
printf("it is a directory");
if(S_ISREG(buf.st_mode))
printf("itisregurlarfile\n");
printf("thenooflinksis%ld\n",buf.st_nlink);
at=ctime(&buf.st_atime);
printf("thetimeoflastaccessis%s\n",at);
mt=ctime(&buf.st_mtime);
printf("themodificationtimeis:%s\n",mt);
ct=ctime(&buf.st_ctime);
printf("time of last change is : %s\n",ct);
if((buf.st_mode &S_IRUSR)==S_IRUSR)
printf("user has read permission\n");
if((buf.st_mode &S_IWUSR)==S_IWUSR)
printf("user has write permisssion\n");
if((buf.st_mode &S_IXUSR)==S_IXUSR)
printf("user has execute permission\n");
if((buf.st_mode &S_IRGRP)==S_IRGRP)
printf("group has read permission\n");
if((buf.st_mode &S_IWGRP)==S_IWGRP)
printf("group has write permission\n");
if((buf.st_mode &S_IXGRP)==S_IXGRP)
printf("group has execute permission\n");
if((buf.st_mode &S_IROTH)==S_IROTH)
printf("others has read permission\n");
if((buf.st_mode&S_IWOTH)==S_IWOTH)
printf("others has write permission\n");
if((buf.st_mode &S_IXOTH)==S_IXOTH)
printf("others has execute permisssion\n");
}

49
Output:

50
7. WriteaCprogramthatillustratesusesoftheopendir, readdir, andclosedirAPIs.

Program:
#include<stdio.h>
#include<fcntl.h>
#include<dirent.h>
#include<unistd.h>
int main()
{
chard[10];
DIR *e;
structdirent*sd;
printf("enterdirnametoopen:");
scanf("%s",d);
e=opendir(d);
if(e==NULL)
printf("dirdoesnotexist");
else
{
printf("dir exist\n");
while((sd=readdir(e))!=NULL)
{
printf("%s\t",sd->d_name);
}
closedir(e);
}
}

Output:

51
8. WriteaCprogramthatcountsthenumber ofblanksinatextfileusingstandard I/O
Program:
#include <fcntl.h>
#include<sys/stat.h>
#include <stdio.h>
intmain(intargc,char**argv)
{
FILE
*fd1;intn,cou
nt=0; char
buf;
fd1=fopen(argv[1],"r");
while(!feof(fd1))
{
buf=fgetc(fd1);
if(buf=='')
count=count+1;
}
printf("\nTotalBlanks=%d",count);
return (0);
}

Output:

52
9. Implement inC, Unixcommand‘cat’usingsystemcalls.
Program:
#include<fcntl.h>
#include<sys/stat.h>
#include<stdio.h>
#include<unistd.h>#defi
ne BUFSIZE 1
intmain(intargc,char**argv)
{
int fd1;
int n;
charbuf;
fd1=open(argv[1],O_RDONLY);
printf("displays filecontents\n");
while((n=read(fd1,&buf,1))>0)
{
write(1,&buf,1);
}
return(0);
}

Output:

53
10. WriteaCprogramthatillustratesthecreationofchild processusingfork systemcall.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.
h>
#include<unistd.h>
int main(int argc,char *argv[])
{
printf("iam:%d\n",(int)getpid()); pid_t
pid=fork();
printf("forkreturned:%d\n",(int)pid);
printf("i am:%d\n",(int)getpid()); return
0;
}

output:

54
11. WriteaCprogramthatillustrateshowtoexecutetwocommandsconcurrentlywitha
command pipe.
Program:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.
h>int main()
{
int pfd[2],p;
pipe(pfd);
p=fork();
if(p==0)//forchild
{
close(pfd[0]);
close(1);
dup(pfd[1]);
execlp("who","who", (char *)0);
}
else
{
close(pfd[1]);
close(0);
dup(pfd[0]);
execlp("wc","wc",(char *)0);
}
}

output:

55
12. WriteaCprogramtoimplementtheKillfunction.
Program:
#include<signal.h>
#include<stdio.h>
#include<unistd.h>voi
d xyz(int n)
{
printf("hello:%d\n",getpid());
signal(2,xyz);
}
voidpqr(intn)
{
printf("frompqr:%d\n",getpid());
}
int main()
{
signal(2,xyz);
if(fork()==0)
{
signal(2,pqr);
kill(0,2);
}
while(1)
return0;
}

Output:

56
13. WriteaCprogramtoimplementtheraisefunction.
Program:
#include <stdio.h>
#include<stdlib.h>
#include<signal.h>
voidsignal_handler(intsignal)
{
/*Displayamessageindicatingwehavereceivedasignal*/ if
(signal == SIGUSR1)
printf("ReceivedaSIGUSR1 signal\n");
/*Exittheapplication*/
exit(0);
}
intmain(int argc,constchar*argv[])
{
/*Displayamessageindicatingweareregisteringthesignalhandler*/ printf("Registering the
signal handler\n");
/* Register the signal handler */
signal(SIGUSR1,signal_handler);
/*Displayamessageindicatingweareraisingasignal*/
printf("Raising a SIGUSR1 signal\n");
/*RaisetheSIGUSR1signal*/
raise(SIGUSR1);
/*Displayamessageindicatingweareleavingmain*/
printf("Finished main\n");
return0;
}

Output:

57
14. Writea Cprogramthatdisplaysthe realtimeofa dayevery60seconds.
Program:
#include<stdio.h>
#include<sys/time.h>
#include<sys/signal.h>
#include<unistd.h>
/*Declarations*/
void main();
inttimes_up();

voidmain()
{
for (;;)
{
times_up(1);
sleep(60);
}
}
inttimes_up(sig)
int sig;
{
long now;
structtms*ptr;
long time();
char*ctime();
time(&now);
printf("Itisnow%s\n",ctime(&now));
return (sig);
}

Output:

58
AdditionalPrograms:

1. Writeashellscripttodisplayfileswhichhasread,writeandexecutepermissions.

Program:
echo“enterafilename”
readf
forfin`ls`
do
if[-w$f–a-r $f–a–x$f] then
echo$f
fi
done

2. Writeashellscripttodisplaythebiggestnumberingiveninputnumbers.
Program:
echo“enteranum”
readnum
if[$1–ge$2]
then
if[$1–ge$3]
then
echo$1“isbiggestnum”
else
echo$3“isbiggest num”
fi
elif[$2–ge$3] then
echo$2“isbiggernum”
else
echo“Biggest numis“$3
fi

3. Write aC program that illustrates the creation of child process using fork system call. One process finds sumof
even series and other process finds sum of odd series.
Program:
#include <stdio.h>
#include<sys/types.h>
#include <unistd.h>
#include <fcntl.h>
intmain()
{
int i,n,sum=0;
pid_t pid;
system(“clear”);
printf(“Enternvalue:”);
scanf(“%d”,&n)
pid=fork();
if(pid==0)
{
printf(“Fromchildprocess\n”);
for(i=1;i<n;i+=2)
{
printf(“%d\”,i);

59
sum+=i;
}
printf(“Oddsum:%d\n”,sum);
}
else
{
printf(“Fromprocess\n”);
for(i=0;i<n;i+=2)
{
printf(“%d\”,i);
sum+=i;
}
printf(“Evensum:%d\n”,sum);
}
}

60

You might also like