UNIT I LINUX AND SHELL PROGRAMMING
ELAVARASHI.M
II CYBER SECURITY iiiiiii
ASSISTANT PROFESSOR
RSMART
INTRODUCTION TO LINUX & SHELL
LINUX
Linux is a versatile, open-source operating system, similar to Unix, that
is freely available for both commercial and non-commercial use. It was
created by Linus Torvalds in 1991 and has become a popular choice for
various applications, including servers, cloud infrastructure, and mobile
devices. Linux is known for its security, stability, and customization
options, making it a popular choice for developers, system
administrators, and DevOps professionals.
• The Linux Operating System is a type of operating system that is
similar to Unix, and it is built upon the Linux Kernel. The Linux
Kernel is like the brain of the operating system because it manages
how the computer interacts with its hardware and resources. It makes
sure everything works smoothly and efficiently. But the Linux Kernel
alone is not enough to make a complete operating system.
• To create a full and functional system, the Linux Kernel is combined
with a collection of software packages and utilities, which are together
called Linux distributions
KERNAL
• The kernel is a computer program that is the core of a computer’s
operating system, with complete control over everything in the system.
It manages the following resources of the Linux system –
• File management
• Process management
• I/O management
• Memory management
• Device management etc
SHELL
• A shell is a special user program that provides an interface for the user
to use operating system services. Shell accepts human-readable
commands from users and converts them into something which the
kernel can understand. It is a command language interpreter that
executes commands read from input devices such as keyboards or
from files. The shell gets started when the user logs in or starts the
terminal
IMPORTANCE OF SHELL
The shell manages the interaction between you and the operating system
by prompting you for input, interpreting that input for the operating
system, and then handling any resulting output from the operating
system. Shells provide a way for you to communicate with the operating
system
1.1 PRINTING IN TERMINAL
• In Linux, printing is an essential function that enables users to create tangible
copies of documents, photos, and other types of data straight from the command
line
• to print a file directly from the Linux terminal console, you can type “lp (file
name)” and it will print to the default printer. For example if we wanted to print
our file called “TEST”, we would type “lp TEST” and it will print to the lab's
default printer.
ECHO
• Echo is a Unix/Linux command tool used for displaying lines of text or string
which are passed as arguments on the command line. This is one of the basic
command in linux and most commonly used in shell scripts.
FOR EXAMPLE
• The command echo "text to be displayed" will output the text "text to be
displayed" on the terminal.
PRINTF
• The 'printf' command in Linux is a versatile tool used to display formatted text,
numbers, or other data types directly in the terminal. Like the 'printf' function in
programming languages like C, the Linux printf command allows users to format
output with great precision, making it ideal for scripts and command-line
operations where customized output is required.
• Syntax for printf command
printf FORMAT printf
[ARGUMENTS...]
FORMAT [ARGUMENTS...]
COLOR AND FORMATTING
• In Linux, color and formatting in the terminal are primarily achieved using ANSI
escape codes and terminal themes. ANSI escape codes, embedded within the
output, allow for controlling text and background colors, styles (like bold, italic),
and other formatting aspects. Terminal themes, often customizable within the
terminal emulator itself, provide pre-set color schemes for the terminal's text and
background.
• ANSI Escape Codes:
ANSI escape codes typically start with \033[, followed by a series of numbers
separated by semicolons, and end with m.
• Color Codes:
• 30-37 are for text colors (black, red, green, yellow, blue, magenta, cyan, white).
• 40-47 are for background colors (black, red, green, yellow, blue, magenta, cyan,
white).
• 1;31m for example, would set the text color to red and make it bold.
1.2 VARIABLE AND ENVIRONMENT
VARIABLE
• In Linux, variables are temporary containers used to store data within a shell
script or process, while environment variables are system-wide configurations
accessible to all processes. Environment variables are passed from parent to child
processes, whereas regular variables are typically local to the current shell session
Variables:
• They hold data during the execution of a script or program.
• They are typically scoped to the current shell session and are not automatically
inherited by child processes.
• They are often used for temporary storage and manipulation of data within a
script.
Environment Variables
• They hold system-wide configurations that affect how programs
and scripts behave.
• They are inherited by child processes from the current shell.
• Examples include PATH (for locating executable files), HOME
(user's home directory), and USER (current user's login name).
• They are used to pass information to programs and scripts that
need to know the system's configuration.
MANUAL METHOD
• In Linux, "manual" refers to the detailed documentation for
commands, utilities, and system calls, accessible using the man
command. This documentation provides information on usage,
options, examples, and more, acting as a reference guide for users and
system administrators
• Use the man command followed by the command name.
FOR EXAMPLE :
To view the manual for a specific command, you simply type .....
man <command_name>. For example, man ls will display the manual
page for the ls command, which lists files and directories.
CUSTOM PRETEND FUCTION
• In Linux, "custom pretend function" can refer to creating custom
commands or aliases to perform actions that mimic existing functions
or behavior. This can be achieved through various methods, including
creating scripts, using aliases, or overriding functions with dynamic
libraries.
• Aliases
provide a way to create short, custom names for frequently used
commands or sequences of commands. This allows you to create
shortcuts for complex operations without writing separate scripts
1.4 MATH WITH SHELL
Integer math: let, $(( )), expr
In Linux shell scripting, let, (( )), and expr are primarily used for performing integer
arithmetic. let is a built-in command for evaluating arithmetic expressions, (( )) is an
alternative way to write let, and expr is a command-line utility used for evaluating
expressions, especially in older systems.
CODE
let a=5+3
echo $a # Output: 8
(( )) Syntax:
• This syntax is an alternative to let for evaluating arithmetic expressions, It's used for arithmetic expansion,
and Example.
Code
b=$((2 * 4))
echo $b # Output: 8
expr syntax :
FLOATING POINT
• Bash shell, we can only perform integer arithmetic. If we want to perform arithmetic involving a
floating point or fractional values, then we will need to use various other utilities, such as awk, bc,
and similar.
• bc is a common tool used to perform floating point arithmetic in shell scripts.
Example:
bash
echo "scale=2; 10 / 3" | bc
# Output: 3.33
TIME MEASUREMENT
• Time measurement in Linux means checking how long a command or process takes to run. It is useful for
testing performance or automation tasks.
Using time Command
• This is the easiest way to measure how long a command takes.
Example:
• bash
time ls
Output:
• sql
• real 0m0.002s → Total time taken (wall clock)
• user 0m0.001s → Time CPU spent in user tasks
• sys 0m0.001s → Time CPU spent in system tasks
ADVACED POWER AND CONVESION
Advanced power and conversion in Linux means:
• Controlling power settings (like shutdown, reboot, sleep).
• Converting units or file formats using command-line tools.
• It helps in power management and data conversion.
Power Management Commands
Task Command Description
• Shutdown sudo shutdown now Turns off the computer immediately
• Reboot sudo reboot Restarts the system
• Sleep systemctl suspend Puts the system to sleep
• Hibernate systemctl hibernate Saves system state and powers off
• Cancel Shutdown shutdown -c Cancels a scheduled shutdown
• Schedule Shutdown sudo shutdown +10 Shutdown after 10 minutes
1.5 FILE DISCRIPTORS AND REDIRECTON
• A file descriptor target is represented by an ampersand followed by the file
descriptor's numerical value. For example, 1>&2 redirects stdout to stderr. To do
the opposite, stderr to stdout, 2>&1 should be used instead.
• In Linux, every time a program runs, it automatically gets three “channels” for input and output:
• Name Number Used For
• stdin 0 Input (like keyboard)
• stdout 1 Output (normal messages)
• stderr 2 Error messages
• These channels are called file descriptors and are just numbers (0, 1, 2).
REDIRECTION
• Redirection means sending output or input somewhere else, like saving
output to a file instead of showing it on the screen.
🔸 Output Redirection
Symbol Meaning Example
> Send output to file (overwrite) echo Hello > file.txt
>> Send output to file (append) echo World >> file.txt
I.6 ARRAYS AND ASSOCIATIVE ARRAYS
• Indexed Arrays
Indexed arrays are the traditional type of arrays, where elements are accessed using
numerical indices, starting from 0.
Code
# Declaring an indexed array
my_array=( "value1" "value2" "value3" )
# Accessing elements
echo ${my_array[0]} # Output: value1
echo ${my_array[2]} # Output: value3
ASSOCIATIVE ARRAY
• Associative arrays, also known as hash tables or dictionaries in other programming languages, use
string keys to access elements instead of numerical indices. They provide a more flexible way to
store and retrieve data using meaningful labels.
Code
# Declaring an associative array
declare -A my_assoc_array
# Adding elements
my_assoc_array["key1"]="value1"
my_assoc_array["key2"]="value2"
my_assoc_array["key3"]="value3"
# Accessing elements
echo ${my_assoc_array["key1"]} # Output: value1
echo ${my_assoc_array["key3"]} # Output: value3
I.7 VISITING ALIASES
• An alias lets you create a shortcut name for a command, file name, or any shell
text. By using aliases, you save a lot of time when doing tasks you do frequently.
You can create a command alias
Example:
• Code
$ alias
ll='ls -la'
gs='git status'
..='cd ..'
This example shows that the alias ll is equivalent to ls -la, gs is equivalent to git
status, and .. is equivalent to cd ...
CREATING AND LISTING
• To create a new directory in Linux, use the mkdir command followed by the
directory name (e.g., mkdir new_folder). To list files and directories, use the ls
command. You can also use ls -l for a long listing, which includes details like
permissions, owner, and file size
• Creating Directories:
1. Use the mkdir command:
Open a terminal and type mkdir followed by the name of the new directory you
want to create. For example: mkdir my_new_directory
2. Multiple directories:
To create multiple directories at once, separate the names with spaces: mkdir dir1
dir2 dir3
REMOVING AND PERSISTING
"removing" typically refers to deleting files, directories, or users, while "persisting" refers to
ensuring changes made to a system, like a live environment, are saved and remain after a reboot. The
rm command is used to delete files, but it doesn't always securely erase data. Persistence, on the
other hand, involves ensuring changes are saved to storage or a persistent drive
Removing in Linux
• Deleting files or directories using rm, rmdir, or unlink.
• Uninstalling software with apt remove, yum remove, etc.
• Removing user accounts or groups.
Persisting in Linux
• Saving configuration changes (e.g., updating /etc/fstab, /etc/sysctl.conf).
• Writing firewall or networking rules that persist after reboot.
• Setting environment variables persistently (e.g., in ~/.bashrc or /etc/environment).
FUNCTION FOR ALIAS LIKE BEHAVIOUR
• In Linux, a function in the shell (like Bash) is a small block of reusable code that
can be called by name, just like an alias — but it is more powerful than an alias.
• ✅ What is an alias?
• An alias is used to create a shortcut for a command.
bash
alias ll='ls -l'
But aliases are limited — they can’t take arguments.
• A function is like an alias that can also accept arguments (inputs) and run multiple
commands.
Simple Syntax of a Function
bash
function_name (){
command1
command2
}
OR
bash
function function_name {
command1
command2
}
SLEEP AND COUNT DOWN
• The sleep command pauses the execution of a script or command for a specific
amount of time.
Basic Usage:
bash
sleep 5
This pauses the terminal or script for 5 seconds.
• s for seconds
• m for minutes
• h for hours
• d for days
COUNT DOWN TIMER
• Countdown Timer in Linux (Using Bash)
Here’s how to create a countdown using a simple loop and sleep.
Example: Countdown from 5 seconds
This loop:
Shows numbers 5 to 1
Waits 1 second between each number
Then prints "Time's up!"
1.8 TERMINAL INFORMATION
• The terminal is a fundamental part of Linux, providing a text-based interface for
users to interact with the system. It's where commands are entered and executed,
and where output is displayed.
Example Commands ls: List files and directories.
• mkdir: Create a new directory.
• mv: Move or rename files/directories.
• cp: Copy files/directories.
• rm: Remove files/directories.
‘TPUT’ (FORMATTING , POSITIONING , SIZE)
• tput : Portable Terminal Control. The tput command allows shell
scripts to do things like clear the screen, underline text, and center text
no matter how wide the screen is. To do these things, it translates the
terminal-independent name of a terminal capability into its actual
value for the terminal type being used
‘STTY’ INPUT CONTROL
• the stty command is used to control terminal input and output. It allows you to set
and modify various terminal I/O characteristics, including speed, rows, columns,
and control characters. Essentially, stty allows you to configure how your terminal
interacts with programs and devices.
• Examples:
• To disable character echoing: stty -echo.
• To reset the terminal to default settings: stty sane.
• To display the current terminal settings: stty -a.
• To set the interrupt character to Ctrl+Z: stty intr ^Z.
• To change the baud rate to 9600: stty speed 9600.
1.9 DATES AND DELAY
• The date command is used to display the current date and time or set a custom
format.
✅ Examples:
• date "+%d-%m-%Y"
• 👉 Shows date like 27-05-2025.
• date "+%H:%M:%S"
• 👉 Shows time like 14:30:45.
• date -d "next Monday"
• 👉 Shows the date of the next Monday
DELAY IN LINUX
• You can pause or delay a command using sleep.
✅ Syntax:
• bash
sleep NUMBER[SUFFIX]
• s = seconds (default)
• m = minutes
• h = hours
• d = days
• Examples:
• sleep 5
• 👉 Waits for 5 seconds.
GETTING CURRENT TIME
• To get the current time in Linux, use the date command with a format.
Show Only Current Time:
You can customize the output using format options:
Format Breakdown:
Format Meaning Example
%H Hour (00–23) 14
%M Minute (00–59) 45
%S Seconds (00–59) 20
EPOCH CONVERSION
• Epoch time (also called Unix time) is the number of seconds since January 1,
1970, 00:00:00 UTC.
SETTING TIME SUDO
• You need root (admin) permission to change the system time in Linux. That's why
we use sudo.
THANKS
method of design. It is a blank space. It is the most common in minimalist design. Keeping white space sounds very simple and then use it properly simple and then use it properly White space is
an advanced method of design. It is a blank space. It is the most common in minimalist design. Keeping white space sounds very simple and then use