π Shell Scripting Notes
π· Table of Contents
- Introduction to Shell Scripting
- Basic Shell Commands
- Variables and Constants
- Input and Output
- Conditional Statements
- Loops
- Functions
- Arrays
- String Manipulation
- File Handling
- Command-line Arguments
- Exit Status & Return Codes
- Error Handling & Debugging
- Signals and Traps
- Process Management
- Scheduling Jobs (cron & at)
- Advanced Topics
- Environment Variables & PATH
- Best Practices
- Useful Built-in Commands
- Resources & Further Reading
1 Introduction to Shell Scripting
- Shell: Interface between user and OS
- Shell Script: File containing a sequence of shell commands
- Common Shells:
bash,zsh,sh,fish -
First script:
#!/bin/bash echo "Hello, World!"
2 Basic Shell Commands
| Command | Description |
|---|---|
ls | List files |
cd | Change directory |
pwd | Show current directory |
touch | Create empty file |
mkdir | Make new directory |
rm | Remove files/folders |
cp | Copy files |
mv | Move/Rename |
cat | Display file contents |
man | Manual/help pages |
3 Variables and Constants
name="Adarsh"
readonly college="VIT"
unset name
$name,${name}β access variable- No spaces around
= readonlymakes variable constantunsetdeletes a variable
4 Input and Output
echo "Enter your name:"
read user
echo "Hello, $user!"
read -p "Prompt" varβ prompt userread -s varβ silent input (e.g., passwords)-
Redirects:
>: overwrite>>: append<: input file
5 Conditional Statements
if [ "$a" -gt 10 ]; then
echo "Greater"
elif [ "$a" -eq 10 ]; then
echo "Equal"
else
echo "Lesser"
fi
[ condition ]or[[ condition ]]test expris same as[ expr ]
6 Loops
For Loop
for i in {1..5}; do
echo "Number: $i"
done
While Loop
while [ $n -lt 5 ]; do
echo $n
((n++))
done
Until Loop
until [ $n -ge 5 ]; do
echo $n
((n++))
done
7 Functions
greet() {
echo "Hello $1"
}
greet "Adarsh"
$1,$2β positional paramsreturnβ return status code (0β255)
8 Arrays
arr=(apple banana mango)
echo ${arr[1]} # banana
echo ${arr[@]} # all
echo ${#arr[@]} # size
9 String Manipulation
str="hello world"
echo ${#str} # length
echo ${str:0:5} # slice
echo ${str/world/Adarsh} # replace
${var#pattern}β remove prefix${var%pattern}β remove suffix
10 File Handling
if [ -f "file.txt" ]; then
echo "File exists"
fi
-ffile exists, regular-dis directory-rreadable-wwritable-xexecutable
11 Command-line Arguments
echo $0 # script name
echo $1 # first arg
echo $# # number of args
echo $@ # all args
12 Exit Status & Return Codes
$?β last command exit codeexit 1β custom exit0is success, non-zero is error
13 Error Handling & Debugging
set -e # exit on error
set -x # debug mode (print commands)
trap 'echo "Error at $LINENO"' ERR
14 Signals and Traps
trap "echo Caught SIGINT" SIGINT
- Used to intercept signals like
SIGINT,SIGTERM - Useful for cleanup scripts
15 Process Management
| Command | Use |
|---|---|
ps | View processes |
top | Live process monitor |
kill | Kill process by PID |
& | Run in background |
wait | Wait for background job |
jobs | List background jobs |
16 Scheduling Jobs (cron & at)
cron β Repeated Jobs
crontab -e
# ββββββββββββββ minute (0 - 59)
# β ββββββββββββββ hour (0 - 23)
# β β ββββββββββββββ day of month (1 - 31)
# β β β ββββββββββββββ month (1 - 12)
# β β β β ββββββββββββββ day of week (0 - 6) (Sunday=0)
# β β β β β
# * * * * * command_to_execute
at β One-time Jobs
echo "bash backup.sh" | at now + 2 minutes
17 Advanced Topics
-
Here Documents:
cat <<EOF Multi-line text block EOF -
Subshells:
(cd dir && ls) -
Arithmetic Expressions:
((a = b + 5)) -
Eval:
cmd="ls -l" eval $cmd -
Sourcing Files:
source config.sh
18 Environment Variables & PATH
- Environment Variable: Global variable accessible by all processes (e.g.,
PATH,HOME) -
Set Temporarily:
export EDITOR=nano -
PATH Variable: Tells the shell where to look for executables
echo $PATH export PATH="$PATH:/my/custom/bin" - To persist changes, modify
~/.bashrcor~/.zshrc
19 Best Practices
- Use
#!/bin/bashshebang - Quote all variables:
"${var}" - Check for errors:
if [ $? -ne 0 ]; then ... - Use functions for reuse
- Comment complex logic
- Prefer
[[ ]]over[ ]
20 Useful Built-in Commands
| Command | Description |
|---|---|
alias | Create shortcut |
type | Show command type |
source | Execute file in current shell |
which | Show command path |
basename, dirname | Path parsing |