Learn the fundamentals of Unix and Bash scripting with practical examples
Unix is a powerful, multiuser, multitasking operating system originally developed in the 1970s.
Unix was developed in 1969 at AT&T's Bell Labs by Ken Thompson, Dennis Ritchie, and others. It was initially created as a simple, multi-tasking system for programmers.
Over the years, Unix evolved into a powerful operating system that became the foundation for many others, including Linux and macOS.
Learn more about Unix history through these classic documentaries:
Unix architecture consists of several components, including the kernel, shell, and file system.
The Unix filesystem is organized in a hierarchical structure, starting from the root (/) directory.
The root directory (/) is the top-level directory in Unix systems.
# Common paths
/Applications/ # User applications
/Library/ # System libraries
/Library/Frameworks/ # System frameworks
# System directory structure
/System/
├── Library/
└── Volumes/
# Directory structure
/Users/
├── username/
│ ├── Documents/
│ └── Desktop/
/Volumes/
├── ExternalDrive/
└── NetworkShare/
# Essential commands location
/bin/ls # List directory contents
/bin/cp # Copy files
/bin/mv # Move files
/sbin/mount # Mount filesystems
# Important configuration files
/etc/
├── passwd # User accounts
├── hosts # Host name resolution
└── ssh/ # SSH configuration
# Common variable data
/var/
├── log/ # System logs
├── mail/ # Mail data
└── spool/ # Print queues
Unix treats everything as a file and supports various file types:
Most common file type, containing data in various formats:
# Example of regular files
-rw-r--r-- 1 user group 2048 Jan 20 14:30 document.txt
-rwxr-xr-x 1 user group 8390 Jan 20 14:35 script.sh
-rw-r--r-- 1 user group 1024 Jan 20 14:40 image.jpg
Special files that contain other files and directories:
# Directory listing
drwxr-xr-x 2 user group 4096 Jan 20 14:45 Documents/
drwxr-xr-x 4 user group 4096 Jan 20 14:50 Projects/
# Common directory operations
ls -la # List directory contents
mkdir dir # Create directory
rmdir dir # Remove empty directory
rm -r dir # Remove directory and contents
Special files that point to other files or directories:
# Symbolic link example
lrwxrwxrwx 1 user group 15 Jan 20 15:00 link -> target
# Creating symbolic links
ln -s target link # Create symbolic link
ls -l link # View link details
readlink link # Show link target
Used for block-oriented devices:
# Block device examples
brw-rw---- 1 root disk 8, 0 Jan 20 15:10 /dev/sda # Hard drive
brw-rw---- 1 root disk 8, 1 Jan 20 15:10 /dev/sda1 # Partition
# Common characteristics:
- Fixed size blocks
- Random access
- Buffered I/O
- Used for storage devices
Used for character-oriented devices:
# Character device examples
crw-rw-rw- 1 root root 1, 3 Jan 20 15:15 /dev/null # Null device
crw-rw---- 1 root tty 4, 0 Jan 20 15:15 /dev/tty0 # Terminal
# Common characteristics:
- Character stream
- Sequential access
- Unbuffered I/O
- Used for terminals and printers
Special files for inter-process communication:
# Named pipe example
prw-r--r-- 1 user group 0 Jan 20 15:20 mypipe
# Creating and using named pipes
mkfifo mypipe # Create named pipe
ls -l mypipe # View pipe details
echo "Hello" > mypipe & # Write to pipe
cat < mypipe # Read from pipe
Used for network and inter-process communication:
# Socket file example
srw-rw---- 1 user group 0 Jan 20 15:25 /tmp/mysql.sock
# Common socket locations
/var/run/*.sock # System service sockets
/tmp/*.sock # Temporary sockets
# Characteristics:
- Bidirectional communication
- Used by network services
- Local IPC mechanism
Core commands for file operations and navigation:
List directory contents
# Basic usage
ls # List files in current directory
ls -l # Long format listing
ls -a # Show hidden files
ls -la # Combine long format and hidden files
ls -lh # Human-readable file sizes
ls -R # Recursive listing
ls -lt # Sort by modification time
Common use cases:
Copy files and directories
# Basic usage
cp file1 file2 # Copy a file
cp -r dir1 dir2 # Copy directory recursively
cp -i file1 file2 # Interactive mode (prompt before overwrite)
cp -p file1 file2 # Preserve attributes
cp file{1,2,3} dir/ # Copy multiple files
cp -v * dir/ # Verbose mode
Common use cases:
Move or rename files and directories
# Basic usage
mv file1 file2 # Rename a file
mv file dir/ # Move file to directory
mv -i file1 file2 # Interactive mode
mv -v file dir/ # Verbose mode
mv dir1 dir2 # Move/rename directory
mv file{1,2,3} dir/ # Move multiple files
Common use cases:
Remove files and directories
# Basic usage
rm file # Remove a file
rm -r dir # Remove directory recursively
rm -f file # Force removal (no prompt)
rm -i file # Interactive mode
rm -rf dir # Force remove directory
rm -v file # Verbose mode
⚠️ Warning:
Print working directory
# Basic usage
pwd # Show current directory
pwd -P # Show physical path (resolve symlinks)
pwd -L # Show logical path (keep symlinks)
# Example output
/home/user/documents
Common use cases:
Change directory
# Basic usage
cd dir # Change to directory
cd # Go to home directory
cd - # Go to previous directory
cd .. # Go up one level
cd ../.. # Go up two levels
cd ~ # Go to home directory
Common use cases:
Directory stack manipulation
# pushd usage
pushd /path # Push directory and change to it
pushd +n # Rotate stack n times
dirs # Show directory stack
# popd usage
popd # Pop top directory and return
popd +n # Remove nth directory from stack
Common use cases:
# Viewing files
cat file.txt # Display entire file
less file.txt # Page through file
head -n 5 # Show first 5 lines
tail -f log # Follow file updates
# Searching content
grep pattern file # Search for pattern
find . -name "*.txt" # Find files by name
locate filename # Quick file search
# Basic text manipulation
cut -d',' -f1 file.csv # Extract first column
sort -n numbers.txt # Sort numerically
uniq -c # Count unique lines
wc -l file.txt # Count lines
# Text streams
echo "hello" | tr a-z A-Z # Convert to uppercase
cat file.txt | grep error | sort | uniq
#!/bin/bash
# Script description
# Author: Your Name
# String variables
name="John"
greeting="Hello, $name!"
# Numeric operations
count=5
((count++))
result=$((5 + 3))
# Arrays
fruits=("apple" "banana" "orange")
echo "${fruits[0]}" # First element
echo "${fruits[@]}" # All elements
echo "${/#fruits[@]}" # Array length
# If statements with file tests
if [ -f "$file" ]; then
echo "File exists"
elif [ -d "$file" ]; then
echo "It's a directory"
else
echo "Not found"
fi
# Case statements
case "$option" in
start)
start_service
;;
stop)
stop_service
;;
*)
echo "Invalid option"
;;
esac
# For loops
for file in *.txt; do
echo "Processing $file"
done
# While loops with read
while IFS= read -r line; do
echo "Line: $line"
done < input.txt
# Until loops
count=0
until [ $count -ge 5 ]; do
echo $count
((count++))
done
# List files and directories
ls # Basic listing
ls -l # Detailed listing
ls -a # Show hidden files
ls -lh # Human-readable sizes
ls -R # Recursive listing
Complete these tasks:
Sample solutions:
ls -la ~
ls -lh
ls -lt
ls -d */
# Change directory
cd /path/to/dir # Go to specific directory
cd # Go to home directory
cd .. # Go up one level
cd - # Go to previous directory
cd ~/Documents # Go to Documents in home
Navigate through the filesystem:
Sample solutions:
cd ~
cd /etc && cd -
cd ../..
cd /var/log/apache2
# Print Working Directory
pwd # Show current directory
pwd -P # Show physical path (resolve symlinks)
pwd -L # Show logical path
Working with pwd:
Sample solutions:
ln -s /var/log logs
cd logs
pwd -P
pwd -L
# Make Directory
mkdir docs # Create single directory
mkdir -p a/b/c # Create parent directories
mkdir -m 755 secure_dir # Create with specific permissions
mkdir dir1 dir2 dir3 # Create multiple directories
Directory Creation Tasks:
Sample solutions:
mkdir -p project/{src,dist,docs}
mkdir -m 700 secure_data
mkdir -p ~/projects/web/{css,js,images}
# Copy files and directories
cp file1 file2 # Copy file
cp -r dir1 dir2 # Copy directory recursively
cp -p file1 file2 # Preserve permissions
cp -i file1 file2 # Interactive mode
Copy Operations:
Sample solutions:
cp *.txt backup/
cp -rp project/ project_backup/
cp file.txt file.txt.$(date +%Y%m%d)
# Move or rename files
mv file1 file2 # Rename file
mv file dir/ # Move file to directory
mv -i file1 file2 # Interactive mode
mv -n file1 file2 # No overwrite
Move and Rename Tasks:
Sample solutions:
for ext in jpg png pdf; do
mv *.$ext ${ext}_files/
done
mv project{,-old}
mv -n *.log backup/
# Remove files and directories
rm file # Remove file
rm -r directory # Remove directory recursively
rm -f file # Force remove
rm -i file # Interactive mode
Removal Operations:
Sample solutions:
rm *.tmp
find . -type d -empty -delete
rm -i *.log
# Create an empty file or update timestamp
touch file.txt # Create a new file
touch existing_file.txt # Update timestamp of existing file
touch -d "2023-01-01" file.txt # Set specific timestamp
File Creation Tasks:
Sample solutions:
touch file1.txt file2.txt file3.txt
touch -d "2023-01-01" file1.txt
# Concatenate and display files
cat file.txt # Display file content
cat file1.txt file2.txt # Concatenate files
cat > newfile.txt # Create a new file from stdin
File Display Tasks:
Sample solutions:
cat myfile.txt
cat file1.txt file2.txt > combined.txt
cat > newfile.txt
# View file contents page by page
less file.txt # View file
less +G file.txt # Start at the end of the file
less -N file.txt # Show line numbers
File Navigation Tasks:
Sample solutions:
less /var/log/syslog
less +G /var/log/syslog
less -N /var/log/syslog
# Display the first lines of a file
head file.txt # First 10 lines
head -n 5 file.txt # First 5 lines
head -c 20 file.txt # First 20 bytes
File Preview Tasks:
Sample solutions:
head -n 15 myfile.txt
head -c 100 myfile.txt
# Display the last lines of a file
tail file.txt # Last 10 lines
tail -n 5 file.txt # Last 5 lines
tail -f log.txt # Follow log file updates
File Monitoring Tasks:
Sample solutions:
tail -n 20 myfile.txt
tail -f /var/log/syslog
# Search for patterns in files
grep "error" file.txt # Search for 'error'
grep -i "error" file.txt # Case-insensitive search
grep -r "pattern" /path # Recursive search in directory
Search Tasks:
Sample solutions:
grep "word" myfile.txt
grep -r "pattern" /path/to/directory/*.txt
# Search for files in a directory hierarchy
find /path -name "*.txt" # Find by name
find /path -type f -size +1M # Find files larger than 1MB
find /path -mtime -7 # Find files modified in the last 7 days
File Searching Tasks:
Sample solutions:
find /var/log -name "*.log"
find /path -mtime -1
# Change file permissions
chmod 755 file.txt # Set rwxr-xr-x
chmod u+x script.sh # Add execute permission for user
chmod -R 700 /path/to/dir # Recursively set permissions
Permission Tasks:
Sample solutions:
chmod 444 myfile.txt
chmod +x myscript.sh
# Change file owner and group
chown user:group file.txt # Change owner and group
chown -R user:group /path/to/dir # Recursively change ownership
Ownership Tasks:
Sample solutions:
chown newuser file.txt
chown -R newuser:newgroup /path/to/dir
# Archive files
tar -cvf archive.tar /path/to/dir # Create an archive
tar -xvf archive.tar # Extract an archive
tar -czvf archive.tar.gz /path/to/dir # Create a compressed archive
Archiving Tasks:
Sample solutions:
tar -cvf myarchive.tar /path/to/dir
tar -xvf myarchive.tar
# Compress files
gzip file.txt # Compress file
gunzip file.txt.gz # Decompress file
gzip -k file.txt # Keep original file
Compression Tasks:
Sample solutions:
gzip *.txt
gunzip file.txt.gz
echo "${/#variable}"
The kernel is the core of the Unix operating system, responsible for:
# Common Unix shells
/bin/sh - Bourne Shell (sh)
/bin/bash - Bourne Again Shell (bash)
/bin/zsh - Z Shell (zsh)
/bin/csh - C Shell (csh)
/bin/tcsh - Enhanced C Shell (tcsh)
# SUID, SGID, and Sticky Bit
chmod u+s file # Set SUID
chmod g+s dir # Set SGID
chmod +t dir # Set Sticky Bit
# Numeric notation
chmod 4755 file # SUID with rwxr-xr-x
chmod 2755 dir # SGID with rwxr-xr-x
chmod 1777 dir # Sticky bit with rwxrwxrwx
# Common environment variables
echo $PATH # Executable search path
echo $HOME # User's home directory
echo $USER # Current username
echo $SHELL # Current shell path
# Setting environment variables
export MY_VAR="value"
PATH=$PATH:/new/path
# Using && and ||
command1 && command2 # Run command2 if command1 succeeds
command1 || command2 # Run command2 if command1 fails
# Using select for menus
select option in "Start" "Stop" "Restart" "Exit"; do
case $option in
"Start") start_service ;;
"Stop") stop_service ;;
"Restart") restart_service ;;
"Exit") break ;;
esac
done