Mastering UNIX Shell Scripting: Complete Notes!

Listen to this Post

UNIX shell scripting is a powerful tool for automating tasks, managing systems, and improving productivity. Whether you’re a beginner or an advanced user, mastering shell scripting can significantly enhance your workflow. Below is a detailed guide covering essential concepts, commands, and practical examples.

Basics of Shell and Shell Scripting

  • The UNIX shell is a command-line interpreter that executes user commands.
  • Common shells include Bash (Bourne Again Shell), Zsh, and Ksh.
  • A shell script is a text file containing a sequence of commands.

Example Script (Hello World):

#!/bin/bash 
echo "Hello, World!" 

Save as `hello.sh`, then make it executable:

chmod +x hello.sh 
./hello.sh 

### **Variables, Control Flow, and Functions**

  • Variables: Store data for reuse.
    name="Undercode" 
    echo "Welcome to $name" 
    
  • Conditionals (if-else):
    if [ $USER == "root" ]; then 
    echo "You are root!" 
    else 
    echo "Run as root!" 
    fi 
    
  • Loops (for, while):
    for i in {1..5}; do 
    echo "Count: $i" 
    done 
    
  • Functions: Reusable code blocks.
    greet() { 
    echo "Hello, $1!" 
    } 
    greet "Admin" 
    

### **Working with Files and Directories**

  • List files:
    ls -l 
    
  • Create/Delete directories:
    mkdir new_folder 
    rm -r old_folder 
    
  • Search files:
    find /home -name "*.txt" 
    
  • File permissions:
    chmod 755 script.sh 
    chown user:group file.txt 
    

### **Text Processing with grep, awk, sed**

  • grep: Search text patterns.
    grep "error" /var/log/syslog 
    
  • awk: Process and analyze text.
    awk '{print $1}' data.txt 
    
  • sed: Stream editor for text substitution.
    sed 's/old/new/g' file.txt 
    

### **Error Handling and Debugging**

  • Exit on error:
    set -e 
    
  • Debug mode:
    bash -x script.sh 
    
  • Log errors:
    command 2> error.log 
    

### **Advanced Scripting Techniques**