0% found this document useful (0 votes)
5 views45 pages

Unix Shell Script Notes Bca 4th Sem

The document provides an overview of the Linux operating system, its architecture, distributions, and applications. It highlights key features such as security, flexibility, and open-source nature, along with popular distributions like Ubuntu and Kali Linux. Additionally, it compares Linux with UNIX, emphasizing differences in source code availability, user interfaces, and portability.
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)
5 views45 pages

Unix Shell Script Notes Bca 4th Sem

The document provides an overview of the Linux operating system, its architecture, distributions, and applications. It highlights key features such as security, flexibility, and open-source nature, along with popular distributions like Ubuntu and Kali Linux. Additionally, it compares Linux with UNIX, emphasizing differences in source code availability, user interfaces, and portability.
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

1

SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Introduction to Linux Operating System


Linux is based on the UNIX operating system. UNIX is a powerful, multi-user,
multitasking operating system originally developed in the 1970s at AT&T Bell Labs.
It laid the foundation for many modern operating systems, including Linux.
 Linux is free and open-source, accessible to everyone.
 This promotes global collaboration and innovation.
 Linux offers efficient performance and strong security.
 It works well across many devices and industries.
Linux combines a wide range of open-source tools and components to form a
complete computing environment. These components include file systems, user
interfaces, system utilities, and application programs all working together to manage
hardware and enable users to interact with their computer systems.

Distributions in Linux
A Linux distribution is a complete operating system built around the Linux kernel,
combined with system software, libraries, and applications. It provides users with
everything needed to run Linux on different types of devices.
 A distribution includes the Linux kernel, system libraries, and essential
software tools.
 Different distributions are designed for different purposes such as
desktops, servers, and embedded systems.
 Each distro comes with its own package manager, desktop environment,
and default applications.
 Users can choose distributions based on performance, stability, ease of
use, or customization level.

Popular Linux Distributions

Around 600 + Linux Distributions are available and some of the popular Linux
distributions are:
 Ubuntu: Ubuntu is a user-friendly Linux distribution mainly used for
beginners, desktops, servers, and cloud computing.
 Debian - A stable and reliable Linux distribution, Debian is widely used
for servers and serves as the base for many other distributions.
 Kali Linux - A security-focused Linux distribution used for penetration
testing, ethical hacking, and digital forensics, Kali Linux.
 MX Linux - MX Linux is a lightweight and fast Linux distribution
designed for older hardware with good stability and performance.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


2
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 Manjaro - A user-friendly Arch-based Linux distribution used for rolling


updates and access to the latest software, Manjaro.
 Linux Mint - A beginner-friendly Linux distribution, Linux Mint, is
designed to be simple and familiar for Windows users.
 Solus - Solus is a modern, independent Linux distribution focused on
desktop performance and simplicity.
 Fedora - A cutting-edge Linux distribution used by developers to work
with the latest technologies, Fedora
 openSUSE - A powerful Linux distribution, openSUSE, is used for system
administration, development, and enterprise environments.
 Deepin - Deepin is a visually attractive Linux distribution focused on ease
of use and a polished desktop experience.
Importance of Linux
Linux is a free, open-source operating system known for its flexibility, stability, and
strong security. It is widely used in personal computing, server environments, and
enterprise systems because of its performance and customization capabilities.
 Offers high security and stability, making it ideal for servers and
development work.
 Fully open-source and free to use, modify, and distribute.
 Highly flexible and customizable to suit different user and industry needs.
 Supported by a large global community and a vast software ecosystem.
Architecture of Linux
Linux architecture refers to the layered structure of the Linux operating system that
defines how its components - such as the kernel, shell, system libraries, and
hardware - interact with each other to manage system resources and execute user
programs efficiently. It has the following components
Architecture of Linux
Linux architecture refers to the layered structure of the Linux operating system that
defines how its components - such as the kernel, shell, system libraries, and
hardware - interact with each other to manage system resources and execute user
programs efficiently. It has the following components:

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


3
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

1. Kernel

The kernel is the core of the Linux operating system that manages hardware
resources and controls communication between software and hardware.
 Handles process management, memory, and device control.
 Prevents conflicts between multiple running programs.
Types of Kernels: Monolithic, Microkernel, Hybrid, Exokernel

2. System Libraries

System libraries provide essential functions that allow applications to interact with
the kernel without needing to access it directly.
 Contain reusable pre-written code for common system operations.
 Act as an interface between applications and the Linux kernel.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


4
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

3. Shell

The shell is the command-line interface that allows users to communicate with the
operating system by entering commands.
 Interprets and executes user commands.
 Acts as a bridge between user actions and kernel processing.

4. Hardware Layer

The hardware layer consists of physical components that execute commands and
provide system resources.
 Includes CPU, RAM, storage, and input/output devices.
 Communicates with the OS using device drivers and kernel services.

5. System Utilities

System utilities are built-in tools that help users manage, configure, and maintain the
operating system.
 Used for tasks like software installation, user management, and
monitoring.
 Simplify system administration processes for both beginners and
administrators.
Applications of Linux Operating System
The Linux operating system is widely used across multiple domains due to its
flexibility, strong security, and open-source nature. It supports a wide range of
applications across different industries, as outlined below.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


5
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

1. Servers and Hosting

 Powers most web servers, cloud platforms, and data centers worldwide.
 Offers high stability, security, and uptime for critical services.

2. Development

 Provides powerful tools and environments for coding, testing, and


debugging.
 Supports multiple programming languages and frameworks.

3. Desktop and Personal Use

 Offers customizable and secure desktop environments.


 Supports daily computing tasks like browsing, office work, and media
usage.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


6
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

4. Cybersecurity

 Widely used for ethical hacking and penetration testing (e.g., Kali Linux).
 Provides advanced tools for threat detection and security analysis.

5. Embedded Systems

 Runs efficiently on low-resource devices like IoT and routers.


 Supports real-time processing and hardware-level control.

6. Supercomputers

 Used in high-performance computing environments worldwide.


 Handles massive scientific calculations and simulations efficiently.

7. Education

 Helps students learn programming, networking, and system administration.


 Free and open-source, making it ideal for academic institutions.
Selecting a Linux Distribution Based on Your Requirements
Selecting a Linux distribution depends on your personal needs, experience level, and
the purpose for which you want to use the operating system. Different distributions
are designed for tasks like development, security, servers, or everyday desktop use,
offering flexibility and customization for every type of user.

For Beginners

 Ubuntu provides an easy-to-use interface with strong community support


for new users.
 Linux Mint offers a Windows-like experience, making it comfortable for
first-time Linux users.

For Advanced Users

 Arch Linux is known for minimalism and deep system customization.


 Gentoo allows full control over system configuration but requires
advanced knowledge.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


7
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

For Developers

 Fedora offers the latest development tools and technologies.


 Debian is highly stable with a large software repository for development
and production.

For Servers

 CentOS provides enterprise-level stability similar to Red Hat Enterprise


Linux (RHEL).
 Ubuntu Server is popular for its ease of use and strong community support.

For Lightweight Systems

 Lubuntu is optimized for low-resource systems and older hardware.


 Puppy Linux is extremely lightweight and runs well on very old
computers.

For Security Professionals

 Kali Linux is designed for penetration testing and ethical hacking with pre-
installed security tools.
 Used widely for cybersecurity training, vulnerability assessment, and
digital forensics.
UNIX is a multitasking and multiuser operating system designed to provide a stable,
secure, and efficient computing environment. It was originally developed at AT&T
Bell Labs and later became the foundation for many modern operating systems.
 It supports the execution of multiple tasks or processes simultaneously.
 It is widely known for its reliability, structured design, and long-term
stability.
 Its design principles have influenced many modern systems such as Linux,
BSD, and macOS.
Key Features
The key features of the UNIX operating system are listed below:

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


8
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

1. Multiuser System

 Multiple users can access the system at the same time without affecting
one another’s processes.
 Each user gets separate permissions and environments to ensure privacy
and secure operations.

2. Multitasking Capability

 UNIX can execute several processes simultaneously through efficient CPU


scheduling.
 Background and foreground tasks can run together, improving productivity
and resource usage.

3. Portability

 Written mostly in the C language, allowing easy movement of UNIX to


different hardware platforms.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


9
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 Only minimal changes are required to adapt UNIX to new systems,


making it widely supported.

4. Hierarchical File System

 Files and directories are arranged in a tree-like structure, starting from the
root /.
 This structure makes navigation, file organization, and data access simple
and systematic.

5. Security and Permissions

 UNIX assigns permissions (read, write, execute) to user, group, and others
for file protection.
 Authentication through usernames and passwords ensures secure access
control.

6. Shell and Scripting Support

 The shell acts as a command interpreter, allowing users to communicate


with the system.
 Shell scripting automates repetitive tasks, making system management
faster and easier.
Layered Structure of UNIX Operating System
The layered structure of the UNIX operating system organizes its components into
hierarchical levels-hardware, kernel, system utilities, and applications to ensure
efficient, secure, and modular system functioning.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


10
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

The following points describe the role and functioning of each layer in the UNIX
architecture:

[Layer-1]: Hardware

 Represents the physical components of the computer, such as the CPU,


memory, storage devices, and input/output hardware.
 All system operations depend on this layer, as it forms the base of the
entire UNIX architecture.

[Layer-2]: Kernel

 The kernel is the core of the UNIX operating system and directly interacts
with the hardware.
 It manages essential tasks such as memory allocation, process scheduling,
file handling, device control, and overall resource management.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


11
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

[Layer-3]: System Programs, Commands, and Utilities

 This layer includes compilers (cc, as, ld), editors (vi, ed), text processors
(nroff), and the shell (sh).
 It also contains common UNIX tools and commands like wc, grep, date,
who, and [Link], which rely on the kernel to perform different functions
such as text processing, file management, and system monitoring.

[Layer-4]: Application Layer

 Represents user-developed or external application programs that run on


top of system utilities and shell environment.
 These applications use underlying layers (system utilities and kernel) to
execute tasks successfully and provide services to the user.
Kernel in UNIX Operating System
The kernel is the core and most essential part of the UNIX operating system. It acts
as the central controlling unit that manages all system resources and enables
communication between hardware and software.
 The kernel directly interacts with the hardware and performs low-level
tasks such as memory allocation, device control, and CPU scheduling.
 It manages processes, files, and system calls, ensuring that programs run
smoothly and securely.
 The kernel provides an interface for applications to request system services
without accessing the hardware directly, ensuring safe and controlled
operations.
 It ensures multitasking, resource management, and protection, making
UNIX stable, efficient, and secure.

Kernel and Its Block Diagram


The kernel and its block diagram illustrate how the UNIX kernel manages system
calls, processes, files, and hardware interactions in a structured manner

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


12
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Here,

[Level 1]. User Level

This layer contains user programs and applications, which request services from the
operating system using system calls. System calls behave like normal C functions,
accessed through libraries linked at compile time.

System Call & Library Interface

 Acts as the communication boundary between user programs and the


kernel, ensuring safe system access.
 C programs use library functions, while assembly programs can invoke
system calls directly.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


13
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

[Level 2]. Kernel Level

The Kernel Level manages core system operations such as processes, files, memory,
and device control by directly interacting with the hardware.

1. File Subsystem

 Handles file-related tasks such as allocation, access permissions, data


retrieval, and storage.
 Provides file-related system calls like open, read, write, close, stat, chmod,
and chown.

2. Buffering & Block I/O

 Regulates data flow between the kernel and storage devices through a
buffering mechanism.
 Works with block I/O device drivers to manage efficient disk read/write
operations.

3. Device Drivers

 Kernel modules that control hardware components like disks, printers, and
terminals.
 Support both buffered block devices and raw devices that bypass
buffering.

4. Process Control Subsystem

 Manages process creation, scheduling, execution, and termination.


 Works closely with the file subsystem and allocates CPU time to running
processes.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


14
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

[Level 3]. Hardware Level

 Consists of physical components such as the CPU, memory, and


input/output devices.
 Generates interrupts that the kernel must handle while managing ongoing
tasks.

Difference Between Unix and Linux


Linux is essentially a clone of Unix. But, basic differences are shown below:

Linux Unix

The source code of Linux is freely The source code of Unix is not freely
available to its users available general public

It has graphical user interface along with


It only has command line interface
command line interface

Linux OS is portable, flexible, and can be


Unix OS is not portable
executed in different hard drives

Different versions of Linux OS


Different version of Unix are AIS, HP-
are Ubuntu, Linux Mint, RedHat
UX, BSD, Iris, Solaris, etc.
Enterprise Linux, etc.

The file systems supported by Linux are as


The file systems supported by Unix are as
follows: xfs, ramfs, vfat, cramfsm, ext3,
follows: zfs, js, hfx, gps, xfs, vxfs
ext4, ext2, ext1, ufs, autofs, devpts, ntfs

Linux is an open-source operating system Unix is a proprietary operating system


that was first released in 1991 by Linus that was originally developed by AT&T
Torvalds. Bell Labs in the mid 1960s.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


15
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Linux Unix

The Unix kernel is modular, meaning that


The Linux kernel is monolithic, meaning
it is made up of a collection of
that all of its services are provided by a
independent modules that can be loaded
single kernel.
and unloaded dynamically.

Unix was originally designed to run on


large, expensive mainframe computers,
Linux has much broader hardware support
while Linux was designed to run on
than Unix.
commodity hardware like PCs and
servers.

User Interface of Linux is Graphical or


User Interface of unix is text-based.
text-based.

Command Line Interface of Linux is Bash, Command Line Interface of unix is


Zsh, Tcsh. Bourne, Korn, C, Zsh.

Different Shells in Linux


SHELL is a program which provides the interface between the user and an
operating system. When the user logs in OS starts a shell for user.
Kernel controls all essential computer operations, and provides the restriction to
hardware access, coordinates all executing utilities, and manages Resources between
process. Using kernel only user can access utilities provided by operating system.
Types of Shells in Linux:
The C Shell -
Denoted as csh
 Bill Joy created it at the University of California at Berkeley. It
incorporated features such as aliases and command history. It includes
helpful programming features like built-in arithmetic and C-like
expression syntax. In C shell:
Command full-path name is /bin/csh,
Non-root user default prompt is hostname %,

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


16
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Root user default prompt is hostname #.

The Bourne Shell -


Denoted as sh
 It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX
shell. It is faster and more preferred. It lacks features for interactive use
like the ability to recall previous commands. It also lacks built-in
arithmetic and logical expression handling. It is default shell for Solaris
OS. For the Bourne shell the:
Command full-path name is /bin/sh and /sbin/sh,
Non-root user default prompt is $,
Root user default prompt is #.

The Korn Shell


It is denoted as ksh
 It was written by David Korn at AT&T Bell Labs. It is a superset of the
Bourne shell. So it supports everything in the Bourne [Link] has
interactive features. It includes features like built-in arithmetic and C-like
arrays, functions, and string-manipulation facilities. It is faster than C
shell. It is compatible with script written for C shell. For the Korn shell
the:
Command full-path name is /bin/ksh,
Non-root user default prompt is $,
Root user default prompt is #.

GNU Bourne-Again Shell -


Denoted as bash
 It is compatible to the Bourne shell. It includes features from Korn and
Bourne shell. For the GNU Bourne-Again shell the:
Command full-path name is /bin/bash,
Default prompt for a non-root user is [Link]$
([Link] the shell version number like bash-3.50$),
Root user default prompt is [Link]#.

T Shell -
Denoted as tsh
 It was originally developed for the Plan 9 operating system, but has since
been ported to other systems, including Linux, FreeBSD, and macOS.
Command full-path name is /bin/tcsh,
Default prompt for a non-root user is abhishekaslk(user):~>
DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES
17
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Root user default prompt is root@abhishekaslk(user):~#.

Z Shell -
Denoted by zsh
 Z Shell (zsh) was created by Paul Falstad in 1990 while he was a student at
Princeton University. Z Shell is an extended version of the Bourne-Again
Shell (bash), with additional features and capabilities.
Command full-path name is /bin/zsh,
Default prompt for a non-root user is abhishekaslk(user)%
Root user default prompt is root@abhishekaslk(user):~#

What are the features of the Bash shell?

Bash (Bourne-Again SHell) is one of the most feature-rich shells available. Some of
its notable features include:
 Programmability: Includes advanced scripting capabilities, loops,
conditionals, and user-defined functions.
 Job Control: Bash allows you to control jobs (processes) directly from the
command line (pausing, resuming, and backgrounding processes).
 Command Line Editing: Interactive editing of command entries and
command history features.
 Aliases and Shell Functions: Allows creating short names for commands
or command sequences and more complex functions for custom
operations.
 Environment Control: Provides extensive control over the environment
that scripts and programs run in.
 Shell Expansions: Bash supports brace expansion, tilde expansion,
parameter and variable expansion, command substitution, and arithmetic
expansion.

How to switch between different shells in Linux?

To switch to a different shell during a session, simply type the name of the shell. For
example, to switch to Zsh:
zsh
To change your default shell, use the chsh (change shell) command followed by the
path to the new shell. You can find the path with which:
chsh -s $(which zsh)
This command will set Zsh as your default shell.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


18
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

What are some lesser-known shells in Linux?

Beyond the commonly used shells, there are several lesser-known shells that provide
unique features:
 mksh (MirBSD Korn Shell): A free implementation of the Korn Shell
programming language and a successor to the public domain Korn shell
(pdksh).
 yash (Yet Another SHell): A POSIX-compliant shell focusing on spec
compliance and small footprint.
 oksh (OpenBSD Korn Shell): An OpenBSD-enhanced version of the Korn
Shell, emphasizing simplicity, efficiency, and correctness.
Table of Difference between Korn Shell and Bash Shell
Korn Shell Bash Shell

The script extension of the KSH shell is The script extension of the Bash shell is
.ksh .sh

The path of the Korn shell in the directory The path of the Bash shell in the directory
structure is /bin/ksh. structure is /bin/sh.

Approximately the Binary size of the Korn Bash interpreter has a binary size of 1.1
Interpreter is somewhere 1.6 MB. MB.

Korn shell uses the print command to print Bash shell uses the echo command to print
the message in the terminal. the message in the terminal.

Korn shell has better support to loop Bash shell can also handle loops better but
handling as compared to the Bash shell. not to the mark as compared to Korn shell

Bash shell is developed by Freeware


The Korn shell is developed by David Software Foundation and it is a newly
Korn and it's older than the Bash shell. created shell as compared to the Korn
shell.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


19
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Korn Shell Bash Shell

There is less number of users using the


Bash shell consists of a large number of
Korn shell and the community is also less
active users and has a large community.
as compared to the Bash shell.

Key Advantages of Shell Scripting


 Task Automation: Shell scripts are excellent for automating repetitive, routine,
and complex tasks, such as file cleanup, data backups, server updates, and log
analysis. By running a script, you can perform a sequence of commands without
manual intervention, saving significant time and effort.

 Consistency and Reliability: Once a script is written and tested, it performs the
exact same steps every time, which eliminates the potential for human error
inherent in manual execution of numerous commands. This ensures consistent
and predictable results across different systems and operations.

 Seamless Integration: Shell scripts can easily integrate different commands,


utilities (like grep , awk , sed ), and even other programming languages (like
Python or Perl). This allows complex data processing pipelines to be built with
relative ease using existing system tools.

 Lightweight and Efficient: Scripts are interpreted, meaning there is no separate


compilation step, which makes them easy to write, modify, and test instantly.
They also use minimal system resources, making them efficient for quick fixes
and small tasks.

 System Management and Monitoring: They provide direct, low-level access to


the operating system's functions and resources, enabling effective system
administration tasks like monitoring disk usage, CPU load, and memory
availability, and triggering alerts when necessary.

 Portability (within Unix/Linux environments): Scripts written for one Unix-like


system (e.g., Linux, macOS) often run on others with minimal or no modification,
as the shell environment (like Bash) is widely available and standardized.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


20
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 Rapid Prototyping: The simplicity and quick execution of shell scripts make
them ideal for rapidly prototyping ideas and testing solutions before committing to
a more complex implementation in a high-level language.
Learning Curve: For basic tasks, the command and syntax are the same as those you would
type directly into the command line, making it relatively easy to get started.

File System Navigation Commands in Linux


Linux file system navigation commands are used to move through directories and
explore the file structure using the command line. They help users locate, access,
and manage files and folders efficiently within the Linux operating system.
 Used to change and view directories
 Helps locate files and understand folder structure
 Enables efficient movement across the file system
 Useful in system administration and troubleshooting
Commonly Used File System Navigation Commands
These commands help you navigate, organize, and manage files and directories
within the Linux file system.

1. pwd (print working directory)

The pwd command shows the current location in the system. It tells you which
folder you're currently in.
pwd

Observation
 The current directory is /home/kali/Templates

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


21
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

2. ls (list files and directories)

The ls command is used to list the files and directories in the current directory. It
provides an overview of what is inside a folder.
ls

Observation
 All the files and folders present inside the current folder is listed.

3. cd (change directory)

The cd command is used to move between folders. You can tell it exactly which
folder you want to go to (like giving it an address), or you can use shortcuts to get
around. Let's look into both the methods.

Moving around nearby folder

If you want to move into a folder that's within the one you're already in, you can just
use its name. For instance, if you're in your home directory and want to reach
downloads.
cd [directory name]
cd Downloads

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


22
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Observation
 Checking the current directory
 Using cd command to change the directory
 Observe the updated directory

Going to a Specific Folder

Imagine telling someone the full address to find your house. Similarly, you can do
the same by giving the complete path to the folder. For example, you want to access
the documents folder inside the username folder.
cd [directory path]
cd /home/username/documents

Observation

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


23
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Directory Structure

 Considering the above directory structure, the active directory was


changed from Downloads to Documents by traversing from the home
directory.

4. mkdir (make directory)

The mkdir command, an abbreviation for "make directory," allows you to create new
folders within your existing file system. This provides a structured way to categorize
and store your files.
Syntax:
mkdir [directory name]
Command:
mkdir GeeksForGeeks

Observation
 User tried to create a new folder named GeeksForGeeks

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


24
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 Changed the directory to newly created directory


 The active directory is updated

5. rmdir (remove empty directory)

The rmdir command, short for "remove directory," enables you to delete empty
directories. This is useful for cleaning up unused folders and maintaining a
streamlined file system.
Syntax:
rmdir [directory_name]
Command:
rmdir GeeksForGeeks

Observation
 Observe that the empty directory was removed.

6. cp (copy)

The cp commad in Linux is used to copy files and directories from one location to
another.
Syntax:
cp [source_file] [location]
Command:
cp ~/Downloads/[Link] ~/Pictures

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


25
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET


Here, copy "[Link]" from Downloads to Pictures while keeping the
original.
Obervation
 Executing the copying command.
 Changing the current active directory for checking.
 Using the list command, we can observe that the [Link] was copied.

7. mv (move)

The mv command in Linux is used to move or rename files and directories from one
location to another.
Syntax:
mv [source_file] [location]
For instance, to move a file named "[Link]" from your Downloads folder to
Documents, you'd use
mv ~/Downloads/[Link] ~/Pictures

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


26
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Observation
 Executing the mv (move) command.
 Changing the current active directory.
 After executing ls (list) command, we can observe that the file has been
transferred.
Difference between Windows and Linux File System
Windows and Linux differ significantly in how they organize, access, and manage
files within their operating systems.

Windows File System

 Uses a drive-based structure such as C:, D:, and E:, where each drive is
treated separately.
 File names are not case-sensitive, meaning [Link] and [Link] are
considered the same.
 Provides simpler file permission management, mainly based on user
accounts.
 Primarily uses the NTFS file system for storing and managing data.
 Designed to be user-friendly and easy to use, especially for beginners.

Linux File System

 Follows a single, unified directory tree structure starting from the root
directory (/).
DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES
27
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 File names are case-sensitive, so [Link] and [Link] are treated as different
files.
 Offers advanced and granular permission control for users, groups, and
others.
 Commonly uses the Ext4 file system, along with support for many other
file systems.
 Highly flexible and powerful, making it suitable for advanced users and
system administrators.
Additional Shortcut Tips
These quick symbols help you navigate the Linux file system more efficiently.

1. ~ (tilde)

This symbol is like a shortcut to your home base. No matter where you are, typing
tilde will always bring you back to your home folder.
cd ~

 The active directory was updated to home.

2. . (dot)

This simply means the folder you're in right now. If you're already inside a folder
and want to work with something there, you can use the dot symbol.

3. .. (double dot)

This means the folder one level above the one you're in, like going up a floor in a
building. If you're deep inside folders and want to go back a step, this will take you
to the bigger folder that contains the one you're in.
cd ..

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


28
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Observation
 The current directory is visible, and we execute the command.
 The active directory is updated.

4. tree: seeing the bigger picture in Linux

This command isn't exactly for moving around, but it helps you see all the folders at
once. It shows how all the folders are connected, like a family tree, so you can
understand the bigger picture.
tree

 All the files and folders of the active directory is listed.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


29
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Writing and executing shell scripts


A shell script is a collection of commands written in a scripting language that is
interpreted by a shell in an operating system such as Linux. The shell acts as
a command-line interface (CLI), allowing users to interact with the operating system
by executing commands.
Shell scripts are commonly used to:
 Automate repetitive tasks
 Execute a sequence of commands
 Simplify system administration
 Improve efficiency and consistency
Writing Your First Shell Script

Step 1: Choose a Text Editor

Before you start writing your shell script, you need a text editor. Popular choices
include Nano, Vim, and Emacs. For beginners, Nano is user-friendly and easy to
use:
nano [Link]

Step 2: Write Your Script

Let's create a simple script that prints "Hello, World!" to the terminal:
#!/bin/bash
# This is a simple shell script

echo "Hello, World!"


Explanation:
 The first line (#!/bin/bash) is called the shebang. It specifies the shell that
should be used to interpret the script.
 Lines starting with # are comments. They are ignored by the shell and help
improve readability.
 The echo command prints text to the terminal.

Step 3: Save and Exit

Save the script by pressing , then to confirm, and finally, to exit.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


30
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Step 4: Make the Script Executable

To run the script, you need to make it executable:


chmod +x [Link]

Executing Shell Scripts

Running the Script

Now that your script is executable, you can run it by typing:


./[Link]
This will execute the commands in your script, and you should see "Hello, World!"
printed to the terminal.

Variables and Input

Shell scripts can use variables to store and manipulate data. Here's an example:
#!/bin/bash

# Get user input


echo "Enter your name:"
read name

# Print a greeting
echo "Hello, $name!"
Run the script, and it will prompt you to enter your name.

Control Flow

Shell scripts support basic control flow structures like , , and loops. Here's a simple
example:
#!/bin/bash

echo "Enter a number:"


read num

if [ $((num % 2)) -eq 0 ]; then


echo "$num is even."
DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES
31
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

else
echo "$num is odd."
fi

Bash Script - File Permissions


what are the file permissions?
File permissions can be described as who, what, and which activities can be done to
a file or directory.
 who refers to users, groups, or others
 what means to add, delete and set
 which means read, write, and execute
Basic list views of file and their permissions
The command we use is ls -l to show us the list of files/directory in the current
folder we are present. This screenshot is a common example to show permission
(using normal centos7 )

List of all files and directories with their permissions

From the above screenshot, let's take a file let's say luser_t04.sh, and see its file
permissions
-rwx rwx rwx 1 root root 0 Feb 27 17:35 luser_t04.sh
1 2 3
(r = read , w= write , x = execute)
 1 represents the permission of the user, they have all the 3 permission to
read, write and execute the file
 2 represents the group to which the file is associated it also has all the
permissions
 3 represent others which also contains all the 3 permissions

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


32
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Manage file permissions


To manage file permissions, we have a command called chmod which we can use to
change the permission of files and directories.

Method to use chmod command

There are 2 methods to use the command


 Symbolic method
 Numeric method

Symbolic Method

Syntax:
chmod whowhatwhich File|directory
 who is u(user) , g(group) , o(other)
 what is to +(add) ,-(remove) ,+(set)
 which is r (read), w(write), x(execute)
Let's see an example: -
Suppose you want to remove read and write permission of group and others from the
file
chmod go-rw <FILE> (can be any file name)
Example:
chmod go-rw luser_t04.sh. The new permission will be like this
-rwx--x--x 1 root root 0 Feb 22 02:28 luser_t04.sh

changing permission using Symbolic method

Numeric method

Syntax:
chmod ### file|directory
#: represents each digit the permission for user, group and others.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


33
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

4 =read 2=write 1 = execute


Let's see the example from above:

Example to understand the numeric method

-rwx--x--x 1 root root 0 Feb 22 02:38 luser_t04.sh


 user permission has been represented by rwx (4+2+1=7)
 group permission has been described as --x (0+0+1 =1)
 other permission has been described as --x ( 0+0+1=1)
Let us take another example of a file
File with permission of 640 what it means in numeric method
-rw- r-- --- 1 root root 0 Feb 22 02:36 [Link]
 user have read(4) and write(2) permission represented by rw- (4+2+0=6)
 the group has read(4) permission represented by r-- (4+0+0=4)
 other have no permission(0) ,represented by --- (0+0+0=0)

Example of file with chmod 640

In this example to set file permission for a file (Example: FILE )


We want the user to be able to read, write and execute files but we don't want groups
to write and execute the file and others to only be able to execute the file so what
command and syntax we should use
Solution:
chmod 741 FILE1 (can be any file name)
The new permission set will be rwx r-- --x for FILE
-rwx r-- --x 1 root root 0 Feb 22 02:28 [Link]

Changing permission using numeric method

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


34
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Script for File permission


We can explain the file permission by creating a simple script to execute and change
the permission of the file after understanding file permissions.

Step-By-Step commands in script:

Step 1. First, we create a file or check if an existing file is there as mentioned in the
screenshot. If the file is not present then we execute the command
touch <FILENAME> (this will create a new file)
Step 2. Our aim is to remove the write permission of others and groups as
mentioned in the screenshot we will execute the command in the script
chmod 744 <FILENAME>
Step 3. Finally, to check if permission is changed or not, we will use
ls -l

The Script

#!/bin/bash

# script to change permission of file

# File variable to store [Link] location


FILE="[Link]"

# to check the file we want to change


# exists or not
if [[ ! -e "${FILE}" ]]
then
echo "creating ${FILE} file"
touch [Link]
fi

# to remove write permission of other and group of file


chmod 744 "${FILE}"

#to check if the permission are removed


ls -l "${FILE}"

Now we will execute this script and check if it works

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


35
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

./file_perm.sh
Output

Output of script

NOTE: In writing script and executing it is important to check permission always


after creating script ls -l command
Using Shebang in Linux
The shebang is an interpreter directive used in Unix-like operating systems. It is a
character sequence, #!, that constitutes the first line of a script. This line specifies
the absolute path to the system interpreter (such as bash, python3, or perl) required
to execute the commands within the script.
You will use a shebang to:
 Tell the system what language a script is in (e.t., bash, python3, node).
 Allow you to run a script directly (e.g., ./[Link]) instead of typing the
interpreter's name first (e.g., python3 [Link]).
 Make your scripts portable so they work on other people's computers.
Practical Application of the Shebang
In some Linux programs that are written in scripting languages like Python, Perl,
and Shell-script, you will see a line right at the top that starts with #!/ like this one:

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


36
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

How It Works: The Three Key Components


There are three distinct concepts that work together.

1. The Shebang (#!)

The name "shebang" comes from its two characters:



#: The "hash" or "sharp" symbol.
 !: The "bang" or exclamation mark.
When you try to run a file, the Linux kernel opens it, sees the #! at the beginning,
and knows it shouldn't run the file itself. Instead, it reads the rest of the line as
a command to run, using the script as the input for that command.

2. The Path

The path is the part after the #!.


#!/usr/bin/python3
 What it does: This directly tells the system to use the python3 program
located in the /usr/bin folder.
 Why it's bad: What if another user's python3 is in /usr/local/bin/python3?
The script will fail.

3. The Executable Permission (chmod +x)

The shebang tells the system how to run the script, but the file's permissions tell the
system if it's allowed to be run.
This is a separate and mandatory step.
 chmod +x [Link] grants executable permission.
 chmod -x [Link] removes executable permission.
Understanding Executable Files in Windows and Linux
We will understand how files are converted into executables in Windows and Linux.
On Windows:
If you've used Windows before, you're likely familiar with executable files,
commonly recognized by their .exe extension. These files are designed to launch
programs and can be run in two simple ways:
 Double-clicking the file in File Explorer.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


37
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Typing its name in the Command Prompt and pressing Enter.


On Linux:
When you transition to Linux, you'll notice a key difference: there's no fixed file
extension for executables. Instead, Linux relies on file permissions to determine
executability. Here's how it works:
 Any file can be made executable by setting the executable flag (using
chmod +x filename).
 When you list files with the ls command, executable files often appear
highlighted in green (depending on your terminal settings).
 To run such a file, use the syntax:
./filename

 When the green file 'greet ' in the above picture was run, it executed some
Linux shell commands. In fact, the file greet is a text file containing one
line of code:
echo Hello, World!
 By default, any text file with lines of Linux shell commands inside it can
be turned into an executable file by setting its Executable Flag, which is
done with the command:
chmod +x <filename>
 But sometimes, you want to run a text file which has commands in Python,
Perl, Ruby, JavaScript, etc. languages instead of Linux Shellscript. That is
where the Shebang comes into the picture.
A Python Example
Suppose we wish to make an executable in Python. We can write a Python script
which will input a number and return its square. We want to run this executable. If

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


38
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

we have Python installed, we can run the file simply by using the following
command:
python <filename>

Question: But suppose we want to run this program without using the Python
command? In other words, can we run the Python script [Link] only using
./[Link] and without using the python command?
Yes, you can, and that's where the Shebang comes into play.

Using a Shebang in Linux


You can use a shebang to tell Linux which interpreter is needed to run the script. For
instance, in the case of a Python file, you will need the python executable. Usually,
this is located in /usr/bin. You will need the complete path to the executable.
 To know the path to the executable, you can use the following command in
Linux.:
which

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


39
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 To use a shebang, you need to know where the interpreter is located in


your computer.
 For the Python interpreter, you will need the location of the Python
executable. Once you know this, the Shebang command is simple :
#!<path-to-interpreter>
 For instance, if your Python interpreter is located in /usr/bin/python like
ours is, then your shebang is:
#!/usr/bin/python
 The next thing to remember is to write your Shebang in the first line of the
Python script, even before any other line. So the overall Python code for
the earlier file [Link] becomes:
#!/usr/bin/python
number = int(input())
print(number * number)
 The last step is to set the executable flag for the Python script. To do this,
we need to run the command
chmod +x [Link]
 And we are ready to run [Link] as an executable.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


40
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Note: The Shebang does not make your file executable by itself. It simply tells Bash
(the shell) where to find the interpreter to run it. You will still need to have the
interpreter installed.
Making Shebangs Portable - Using env
When you write a script with a shebang (#!), it might not work on another machine
because different systems can have interpreters (like Python or [Link]) installed in
different locations. To make your shebangs portable across all systems, you can use
the env command.
 env itself is always located in the same place on all Linux machines:
/usr/bin/env
 So you can use env to make your shebangs portable:
For Python:
#!/usr/bin/env python3

For Node-JS (if the script is in Javascript):


#!/usr/bin/env node

For Perl:
#!/usr/bin/env perl

Executable Path and Shell Commands


When you use an executable script in Linux with a shebang, you can make it become
a shell command! To do this, you need to place it in a PATH location. A PATH
location is a special folder in your Linux filesystem, and all executables inside a
PATH location can be used like commands in Linux.
There are two ways to do this:

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


41
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

1. You can look up the existing PATH locations, find one that is to your
liking, and place your executable script file there. Remember to set the
executable flag with chmod +x <filename> after you move the file there.
2. You can add the folder in which your script file is located to the PATH
variable, and make the file a command.
Below, we will discuss both of these methods.

Adding Your File to a PATH Location


 First, look up the existing PATH locations using this command:
echo $PATH | sed "s/:/\\n/g"
 This will list all the PATH locations in your terminal:

 Notice that not all of the folders listed here are accessible to you without
sudo, since they do not belong inside your Home directory. The most
preferred location is
/home/user/.local/bin
 If this folder doesn't exist, you can create it and add it to the list by
following the instructions under the next subheading. Place the file inside
that location and make sure that the executable flag is set. The file then
becomes a command.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


42
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

Adding a Folder to the PATH List


In general, it is a good idea to make yourself a new directory, add all your
executable script files there, and then add that directory to the PATH locations. This
is especially useful if you do not already have a folder named bin inside ~/.local
directory.
1. First, make the folder which you need to add to PATH.
If the folder already exists, then you can skip this step.
 If it doesn't exist, then you can make it - either using the terminal
command mkdir, or using the GUI.
2. Second, not the path address of the folder. For instance, if the folder is named
mypath and it is inside my home directory, then the location will be
/home/user/mypath
3. Third, open the .bashrc file in a preferred editor. This is a hidden file inside the
home folder. You can see it in your GUI by using Ctrl+H to view hidden files, and
then double-click on it. Alternatively, inside a terminal, you can use nano, vi, or vim
to open the file with a command:
nano ~/.bashrc
 Remember, this is a very important system file. Do not mess with this file
unless you know what you are doing! Simply add one line at the end of the
file, with this content:
export PATH="$PATH:<your-directory-path>"
 For instance, if the directory is /home/user/mypath, then we can use the
command:
export PATH="$PATH:/home/user/mypath"
4. The last step is to close and reopen your terminal.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


43
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

All terminals you open from this point on will treat executable files inside mypath as
commands. If you do not want to close and reopen your terminal, simply run the
command
. ~/.bashrc

It will update itself and your executable file with a Shebang will be
available as a command.
Remember: Your script must have a correct Shebang for it to become a command!
Some Other Uses
Shebangs allow you to choose the interpreter which runs a script, so that the user
does not have to select the interpreter at run time. This can be used to turn a script
into a command, but it also has some other uses. We are going to go over some of
them.

1. Ensuring Compatibility

Different Linux and UNIX distributions use different default shells, which can cause
scripts to behave inconsistently across systems.
 Various distros use different default shells (e.g., Bash, Zsh).
 Scripts may behave differently depending on the shell used.
 Users can override their default shell, leading to compatibility issues.
 To ensure consistency, specify the shell explicitly in the shebang line (e.g.,
#!/bin/sh).
Hence, we can ensure that our script runs identically on all of these systems by
writing a script for the Bourne Shell using this shebang:
#!/bin/sh

2. Specifying Interpreter Version

Different versions of the same shell, such as Bash, can have varying features and
security vulnerabilities. Older enterprise systems often run outdated shells, which
may expose them to risks.
 Older Bash versions may have security issues.
 Enterprises use outdated systems due to licensing limits.
 Installing the latest Bash improves security.
 A custom shebang can set the new Bash as default.
For instance, to ensure that the script runs with Bash 5.2, they can use:
#!/bin/bash-5.2

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


44
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 When a new Bash version (e.g., 5.3) is installed, all scripts would need
updated shebangs. To avoid this, sysadmins create a symlink (shortcut)
named like bash-latest, pointing to the newest Bash version.
 Then the shebang simply points to this symlink:
#!/bin/bash-latest
 When a later version of Bash is installed, the symlink is deleted and a new
one is created at the same location, with the same name, but pointing to the
newer version of Bash.

3. Preventing Direct Execution

Sometimes you don't want a shell-script file to be executed. Maybe you


only want it to be invoked internally, using commands like source or using
the [Link] function in Python.
 If you make a software with such a script, and you want to prevent a user
from unexpectedly running the script, you can deliberately use a shebang
which points to an executable that cannot interpret the script.
 A common choice of such an executable is false, which returns a non-zero
value to the shell (to indicate an error), and does nothing.
To disable a script from being run in the shell by a user who didn't read your
README file, just use this shebang:
#!/usr/bin/false
You can still run a script with such a shebang using the source keyword, but it
cannot be run directly as an executable.
Possible Malicious Use
In Linux, a shebang (#!) defines which interpreter should execute a script. While it’s
a useful feature, it can also be misused to run malicious executables, making it
important to verify before executing unknown scripts.
 Defines the interpreter path (e.g., #!/bin/bash).
 Can be altered to launch harmful programs.
 Always check the shebang line before running unknown scripts.
 It may look like a comment, but it’s executed by the system.
 Verify before using chmod +x to make scripts executable.
Advanced Shebang Options
You can use the shebang for more than just Python and Bash.
 #!/usr/bin/env bash A portable shebang for a Bash script.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES


45
SRI AKSHAYA DEGREE COLLEGE OF MGMT. HOSPET

 #!/bin/sh Use this for maximum compatibility. /bin/sh is the original, basic
shell. If your script works with this, it will run on almost any Unix-like
system (Linux, macOS, BSD, etc.).
 #!/usr/bin/env node For a [Link] (JavaScript) script.
 #!/usr/bin/env perl For a Perl script.
 #!/usr/bin/false This is a clever trick to prevent a script from being
executed. false is a tiny program that does nothing and immediately exits
with a failure status. This is sometimes used for library files that should
only be "sourced" (source ./[Link]), not run directly.

DEPT . OF BCA BCA 4TH SEM SHELL SCRIPTING NOTES

You might also like