πŸ“œ Shell Scripting Notes


πž·‚ Table of Contents

  1. Introduction to Shell Scripting
  2. Basic Shell Commands
  3. Variables and Constants
  4. Input and Output
  5. Conditional Statements
  6. Loops
  7. Functions
  8. Arrays
  9. String Manipulation
  10. File Handling
  11. Command-line Arguments
  12. Exit Status & Return Codes
  13. Error Handling & Debugging
  14. Signals and Traps
  15. Process Management
  16. Scheduling Jobs (cron & at)
  17. Advanced Topics
  18. Environment Variables & PATH
  19. Best Practices
  20. Useful Built-in Commands
  21. 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 =
  • readonly makes variable constant
  • unset deletes a variable

4 Input and Output

echo "Enter your name:"
read user
echo "Hello, $user!"
  • read -p "Prompt" var β€” prompt user
  • read -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 expr is 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 params
  • return β€” 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
  • -f file exists, regular
  • -d is directory
  • -r readable
  • -w writable
  • -x executable

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 code
  • exit 1 β€” custom exit
  • 0 is 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 ~/.bashrc or ~/.zshrc

19 Best Practices

  • Use #!/bin/bash shebang
  • 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

21 Resources & Further Reading


This site uses Just the Docs, a documentation theme for Jekyll.