SHELL PROGRAMMING
INDEX
●
Environmental Variables
– What are environmental variables
– Key-value concept
– Shell variable vs Env variable
– How system uses PATH
– Creating variables-no space rule
– $ accessing variables
– Export
– Subshell concept
Shell Basics
– Introduction
– Shell Scripting
– Types of Shell
– Intercative vs Non Interactive Shell
– Why Shell Scripting
Linux File System
– Directory structure
●
Variables
– Basics
– Rules for Variables
– Accessing Variables
– Read command
– Unset
– Readonly Variables
Script Execution
– Shebang(#! bin/bash)
– Method 1(./script .sh)
– Method 2(sh [Link])
– Difference between both methods
●
Compiler vs Interpreter
– Speed,Portability and Execution method
●
Shell Customization
●
File name Substitution(WILDCARDS)
●
Quoting
●
TEST COMMAND
– Numeric Comparison
– String Comparison
– Usage in conditions [ ]
FLOW CONTROL
– If statements
– Case statement
●
LOOPS
– For
– While
– Until
– Loop control
●
Break,continue
●
Special Variables
●
Functions
●
File Descriptors
●
I/O Redirection
●
Pipes
●
Internal vs External Commands
●
Alias
●
Assignment
Environmental Variables
What are environmental variables ?
●
Special variables used by the OS and shell to store configuration
information.
●
They affect the behavior of processes and programs.
●
Examples: $HOME, $PATH, $SHELL.
●
Commands to view env variables
– Printenv
– Env
– Echo $variable_name
Environmental Variables
Shell Variable vs. Environmental Variable
●
Shell Variables
– Created and used inside a single shell session
– Not available to child processes
●
Environmental Variables
– These are exported variables
– Available to current shell,child processes/subshells.
Environmental Variables
How system uses $PATH variable
●
The PATH environment variable stores a list of directories where the shell looks
for executable programs.
●
When you run a command (like ls), the system searches these directories in
order to find the executable file.
●
If the command is not found in any PATH directory, the shell returns a
“command not found” error.
●
type command is used to know whether the command is built in or not.
●
$ is used to access variables in shell.
Shell Basics
– Special program/Application
– Shell is a environment provided for the user interaction.
user interact with the system through shell scripting.
– Allow you to execute commands.
– command interpreter.
– Uses built in commands/syntax
Shell Basics
Why do we need Shell Scripting
●
To do repetitive tasks
● To do automation of tasks such as Back-ups, disk space ,
log monitoring
●
Batch processing of commands
Shell Basics
Types of Shell
●
sh (Bourne Shell) – Basic original Unix shell
●
bash (Bourne Again Shell) – Most common Linux shell
●
ksh (Korn Shell) – Advanced scripting features
●
csh / tcsh – C-like syntax, interactive use
Shell Basics
-> Interactive Shell
●
User types commands manually and gets immediate
output
●
Runs in foreground (terminal session)
-> Non - Interactive Shell
●
Executes commands from a script/file
●
No user input during execution
Linux File System
● Linux file system is a hierarchical structure starting from root directory /.
● Everything in Linux is treated as a file .
● /bin contains essential user command binaries (basic tools). - Tool Room
● /etc stores system configuration files. - HR/Admin office
● /home contains personal directories of users. - Employee cabins
● /var stores variable data like logs and temporary files. - Records room
● /dev contains device files representing hardware. -hardware
● /usr stores user-installed applications and libraries. - library centre
● /tmp is used for temporary files. - notice boards
● /root is the home directory of the root (admin) user. - director
Variables
Rules for defining variables
●
Creating variables
variablename=value
●
Name of the variables can contain only
Letters (a to z or A to Z ),
Numbers (0 to 9) or
The underscore character( _ )
●
Variables name should begin with either an alphabet or an
underscore.
Variables
Accessing a variable
●
To access a value stored in a variable, prefix its name
with the dollar sign ($)
– echo $variablename
●
Value of the variable is substituted when character
precedes the variable name.
●
Dollar sign is used to access the variable's value,not to
define it.
Variables
Read
●
read is used to take input from the user in shell scripts
●
read var stores user input into variable var
●
-p → prints prompt message before input
– read -p "Enter name: " name
●
-n → limits number of characters to read
– read -n 5 code
●
-d → stops reading input at a given delimiter
– read -d ":" input
Variables
Read-only
●
readonly makes a variable constant (cannot be changed or
deleted)
●
Once set, value cannot be modified
●
Syntax: readonly name="Ravi"
●
Trying to change it gives error
●
name="John" # not allowed
●
Used to protect important values in scripts
Variables
Unset
●
unset is used to remove a variable from memory
●
Syntax: unset var_name
●
After unsetting, variable has no value
●
name="Ravi"
●
unset name
●
echo $name # empty output
●
Used to clear variables no longer needed
Shell Execution
Shell Execution
●
Shebang #!/bin/bash
●
It tells the system which interpreter to use
to run the script.
●
#! -> these are the magic characters that
indicate “this file is a script”.
●
/bin/bash -> the path to bash shell that
will execute the script.
Compiler [Link]
Shell Customization
Shell Initialisation
● Global
– /etc/[Link] → system wide access
● Local
– ~/.profile → home dir, user level env settings.
– ~/.bashrc → home dir,user level intercative shell
– ~/.bash_logout → commands to run when user logs out.
Shell Customization
1. Print login message for the a specific user → ~/.bashrc
2. Print login message for all the user→ ~/.profile (or)
/etc/[Link]
3. Modifying environmental variables →~/.bashrc
- export PATH
Filename Substitution
Quoting in Shell
– Quoting can be done in three ways
● Using the backlash(\)
● Using the single quote(')
● Using the double quote(“)
Test Command
In shell scripting,the test command ( [ ] ) is used to evaluate
expressions and return true(0) or flase(1).
Comparison Result
exp1 -gt exp2 True if exp1 is greater than exp2
True if exp1 is greater than or equal
exp1 -ge exp2 to exp2
exp1 -lt exp2 True if exp1 is less than exp 2
True if exp1 is less than or to equal
exp1 -le exp2 exp2
True if both the expression equal are
exp1 -eq exp2
True if both the expression not are
exp1 -ne exp2 equal
Test Command
String comparison Result
str1 = str2 True if both the strings are equal
str1 != str2 True if both the strings are not equal
-n str1 True if the string is not NULL
-z str1 True if the string is NULL
Flow control
-> If
Syntax : if [ condition ]; then
#commands to execute if condition is true
fi
● Example:
Flow control
-> If else
Syntax : if [ condition ]; then
#if block
else [ condition ]; then
#else block
fi
● Example:
Flow control
-> Case statement
Syntax : case variable in
Pattern1)
#commands
;;
Pattern2)
#commands
;;
*)
#default commands
;;
esac
Flow control
-> Case statement
Loops
->Loops are used to execute a set of commands repeatedly until a condition is met.
● For
– used when the number of iterations are known.
– Syntax :
for variable in list
do
# Commands
done
Loops
-> Perform calcuation (())
-> Get result $(())
-> Command substitution $()
Loops
● While
– Runs until the condition is true.
– Syntax :
while [ condition ]
do
# Commands
done
Loops
● Until
– Runs until the condition becomes true..
– Syntax :
until [ condition ]
do
# Commands
done
Loop Control Statements
● Break -> used to exit loop immediately.
● Continue-> skips current iteration
Special Variables
$0 -> script name
$1 ,$2 ,...-> arguments
$# -> argument count
$@ -> all arguments (seperate)
$? -> exit status
Functions
->
A block of code that
performs a specific task
and can be reused
multiple times.
●
Method 1
Functions
-> Calling a function – just by
the name of the function. Example ->
add
●
Returning values in Functions
●
Method 1 -> return
Used to return numeric values
– only(0-255).
Return does not return Strings
– Used for status codes.
–
●
Method 2 -> echo
Used to return actual values
Functions
-> Capturing
output from a
function
Example ->
– result =$(add)
File Descriptors
– File Descriptors are numeric identifiers used by the system
to handle input and output streams.
– Every process in Linux has 3 default file descriptors.
0 -> std input(stdin) takes input
1 -> std output(stdout) displays output
2 -> std error(stderr) displays errors.
I/O Redirection
– I/O Redirection is used to change the default input/output location of a command
– Instead of a keyboard/screen, we can use files.
– Output Redirection
> (overwrite) , >> (append)
– Input Redirection
< (takes input from a file instead of keyboard.
● wc < [Link]
– Piping
● Sends output of one command as input to another command
● Cat [Link] | sort
Internal vs. External Commands
– Internal Commands
●
Executed directly by shell
●
No new process is created
●
Cd,echo,pwd,history->faster
– External Commands
●
Exist as seperate executable files in the file system
●
Shell creates a new process to execute them.
●
Ls,grep,sort,cat
– Alias
●
Only valid in the current shell unless added to .bashrc
●
alias ls=‘ls -al’
Thank You