ReadInput
π₯ Reading User Input
π Overview
π― Master Reading User Input in Shell Scripts
This guide covers the
readcommand and its various options for creating interactive shell scripts that accept user input with prompts and validation.
π What This Guide Covers
- π₯ Read Command Basics - Getting user input
- π¬ Prompt Messages - Displaying prompts to users
- π Secret Input - Reading passwords securely
- π― Read Options - Various flags and parameters
- π Examples - Practical input scenarios
- β Best Practices - Input handling recommendations
π₯ What is the Read Command?
The read command in Bash is used to get user input from the keyboard. It provides flexible options for prompting users and storing their input in variables. The read command is essential for creating interactive shell scripts.
Key Features:
- Accepts user input from standard input
- Stores input in variables
- Supports prompt messages
- Can hide input (for passwords)
- Flexible with multiple options and arguments
π§ Read Command Syntax
Basic Syntax
read variable_name
Syntax with Options
read [options] variable_name
Common Options
| Option | Description | Example |
|---|---|---|
-p | Display prompt message | read -p "Enter name: " name |
-s | Silent mode (hide input) | read -s password |
-t | Timeout in seconds | read -t 5 input |
-n | Read N characters | read -n 1 char |
-r | Raw input (no escaping) | read -r text |
π₯ Basic Read Examples
Example 1: Simple Read
#!/bin/bash
# Script: simple_read.sh
# Purpose: Read a single value from user
read name
echo "Hello ${name}"
Usage:
$ ./simple_read.sh
John
Hello John
Example 2: Read Multiple Values
#!/bin/bash
# Script: multiple_read.sh
# Purpose: Read multiple values from user
read name
read age
echo "Hello ${name}, and your age is ${age}"
Usage:
$ ./multiple_read.sh
John
25
Hello John, and your age is 25
Example 3: Read Without Variable (Using $REPLY)
#!/bin/bash
# Script: reply_read.sh
# Purpose: Read input without specifying a variable
echo "Enter Name: "
read
echo "Name: $REPLY"
Output:
Enter Name:
devopsgurupro
Name: devopsgurupro
Why It Works:
- When you use
readwithout specifying a variable name, the input is automatically stored in the special variable$REPLY $REPLYis a built-in Bash variable that holds the last input from thereadcommand- This is useful when you don't need to store the value in a named variable
- You can access the input using
$REPLYanywhere in your script - If you call
readagain without a variable,$REPLYwill be overwritten with the new input
π¬ Read with Prompt Messages
Example 1: Single Prompt
#!/bin/bash
# Script: prompt_read.sh
# Purpose: Read with prompt message
read -p "Please enter your name: " name
echo "Hello ${name}"
Output:
Please enter your name: devopsgurupro
Hello devopsgurupro
Example 2: Multiple Prompts
#!/bin/bash
# Script: user_info.sh
# Purpose: Collect user information
read -p "Please enter your name: " name
read -p "Please enter your age: " age
read -p "Please enter your city: " city
echo "Name: ${name}"
echo "Age: ${age}"
echo "City: ${city}"
Output:
Please enter your name: devopsgurupro
Please enter your age: 25
Please enter your city: New York
Name: devopsgurupro
Age: 25
City: New York
π Reading Secret Input (Passwords)
Example 1: Simple Password Input
#!/bin/bash
# Script: password_read.sh
# Purpose: Read password securely
read -p "Please enter your password: " -s password
echo ""
echo "Password received (length: ${#password})"
Output:
Please enter your password:
Password received (length: 8)
Example 2: Username and Password
#!/bin/bash
# Script: login.sh
# Purpose: Read username and password
read -p "Enter Username: " username
read -sp "Enter Password: " password
echo ""
echo "Username: ${username}"
echo "Password: ******* (hidden)"
Output:
Enter Username: devopsgurupro
Enter Password:
Username: devopsgurupro
Password: ******* (hidden)
π Complete Interactive Script Examples
Example 1: User Registration Form
#!/bin/bash
# Script: registration.sh
# Purpose: Collect user registration information
echo "=== User Registration Form ==="
read -p "Enter your name: " name
read -p "Enter your email: " email
read -p "Enter your age: " age
read -sp "Enter your password: " password
echo ""
echo ""
echo "=== Registration Summary ==="
echo "Name: ${name}"
echo "Email: ${email}"
echo "Age: ${age}"
echo "Password: ******* (hidden)"
Output:
=== User Registration Form ===
Enter your name: devopsgurupro
Enter your email: [email protected]
Enter your age: 25
Enter your password:
=== Registration Summary ===
Name: devopsgurupro
Email: [email protected]
Age: 25
Password: ******* (hidden)
Example 2: Interactive Menu
#!/bin/bash
# Script: menu.sh
# Purpose: Create an interactive menu
echo "=== Main Menu ==="
echo "1. Option One"
echo "2. Option Two"
echo "3. Option Three"
read -p "Select an option (1-3): " choice
case $choice in
1)
echo "You selected Option One"
;;
2)
echo "You selected Option Two"
;;
3)
echo "You selected Option Three"
;;
*)
echo "Invalid option"
;;
esac
Example 3: Confirmation Prompt
#!/bin/bash
# Script: confirm.sh
# Purpose: Ask for user confirmation
read -p "Do you want to continue? (yes/no): " response
if [ "$response" = "yes" ]; then
echo "Continuing..."
else
echo "Cancelled."
fi
π― Read Command Options
Example 1: Timeout Option
#!/bin/bash
# Script: timeout_read.sh
# Purpose: Read with timeout
read -t 5 -p "Enter something (5 seconds): " input
if [ -z "$input" ]; then
echo "No input provided (timeout)"
else
echo "You entered: ${input}"
fi
Example 2: Read N Characters
#!/bin/bash
# Script: char_read.sh
# Purpose: Read specific number of characters
read -n 1 -p "Press any key to continue: " key
echo ""
echo "You pressed: ${key}"
Example 3: Raw Input
#!/bin/bash
# Script: raw_read.sh
# Purpose: Read raw input without escaping
read -r -p "Enter path (with backslashes): " path
echo "Path: ${path}"
Example 4: Read into Array
#!/bin/bash
# Script: array_read.sh
# Purpose: Read multiple values into an array
read -p "Enter names as per your choice: " -a names
echo "You have entered names: ${names[0]}, ${names[1]}, ${names[2]}"
Output:
Enter names as per your choice: dgpro wahid sameer
You have entered names: dgpro, wahid, sameer
Explanation:
-aflag reads input into an array variable- Each word separated by space becomes an array element
- Access array elements using
${array[index]} ${names[0]}= first name (dgpro)${names[1]}= second name (wahid)${names[2]}= third name (sameer)
β Best Practices
- Always use
-pflag to display clear prompts - Use
-sflag for sensitive information like passwords - Validate user input before using it
- Provide clear instructions to users
- Use meaningful variable names
- Handle empty input gracefully
- Use quotes around variables:
"${variable}" - Test scripts with various inputs
- Provide default values when appropriate
π Navigation
β¬ οΈ Previous: Module 2: System-Defined Variables
π Current Location: Reading User Input (You are here)
β‘οΈ Next Step: Command-Line Arguments
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Read: gnu.org/software/bash/manual/html_node/Bash-Builtins.html
- π Shell Scripting Guide: tldp.org/LDP/abs/html/internal.html
- π‘ Interactive Scripts: linuxcommand.org/lc3_wss0120.php
π Excellent! Reading User Input Complete! π
CommandLineArgument
π Command-Line Arguments
π Overview
π― Master Command-Line Arguments in Shell Scripts
This guide covers how to pass and process command-line arguments in shell scripts, including positional parameters and special variables for handling script inputs.
π What This Guide Covers
- π₯ Arguments Basics - Understanding command-line arguments
- π’ Positional Parameters - Accessing arguments by position
- π― Special Variables - Built-in variables for argument handling
- π Examples - Practical argument usage
- π Looping Arguments - Processing multiple arguments
- β Best Practices - Argument handling recommendations
π₯ What are Command-Line Arguments?
Command-line arguments are inputs passed to a script during execution. Instead of getting input from user interaction or hardcoding values, arguments are provided when running the script. This makes scripts more flexible and reusable.
Key Characteristics:
- Passed during script execution
- Separated by spaces
- Accessed using positional parameters
- Can be processed using special variables
- Enable dynamic script behavior
π’ Positional Parameters
Command-line arguments are passed in a positional way, meaning they are accessed based on their position in the command line.
Syntax
${1} # First argument
${2} # Second argument
${3} # Third argument
# ... and so on
Example 1: Basic Positional Parameters
#!/bin/bash
# Script: greet.sh
# Purpose: Greet user with name and age
name=${1}
age=${2}
echo "Hello my name is ${name} and my age is ${age}"
Usage:
$ ./greet.sh devopsgurupro 25
Hello my name is devopsgurupro and my age is 25
Example 2: Accessing Multiple Arguments
#!/bin/bash
# Script: display_args.sh
# Purpose: Display all passed arguments
echo "Argument 1: ${1}"
echo "Argument 2: ${2}"
echo "Argument 3: ${3}"
echo "Argument 4: ${4}"
echo "Argument 5: ${5}"
Usage:
$ ./display_args.sh dgpro wahid sameer john alice
Argument 1: dgpro
Argument 2: wahid
Argument 3: sameer
Argument 4: john
Argument 5: alice
π― Special Variables for Arguments
Special Variable Reference
| Variable | Description | Example |
|---|---|---|
| ${0} | Script name itself | ./script.sh |
| ${1}, ${2}, ... | Positional arguments | ${1} = first arg |
| $# | Total number of arguments | 3 (if 3 args passed) |
| $@ | All arguments (quoted) | "$@" preserves spaces |
| $* | All arguments (unquoted) | $* joins with spaces |
| $? | Exit status of last command | 0 = success |
Example 1: Script Name and Argument Count
#!/bin/bash
# Script: info.sh
# Purpose: Display script info and argument count
echo "Script name: ${0}"
echo "Total arguments: $#"
echo "Arguments: $@"
Usage:
$ ./info.sh dgpro 25 "New York"
Script name: ./info.sh
Total arguments: 3
Arguments: dgpro 25 New York
π― Special Variables for Arguments
Special Variable Reference
| Variable | Description | Example |
|---|---|---|
| ${0} | Script name itself | ./script.sh |
| ${1}, ${2}, ... | Positional arguments | ${1} = first arg |
| $# | Total number of arguments | 3 (if 3 args passed) |
| $@ | All arguments (quoted) | "$@" preserves spaces |
| $* | All arguments (unquoted) | $* joins with spaces |
| $? | Exit status of last command | 0 = success |
Understanding $@ (All Arguments)
The $@ variable represents all command-line arguments passed to the script. It's one of the most important special variables in shell scripting.
How $@ Works:
- Stores All Arguments -
$@contains every argument passed to the script - Preserves Spaces - When quoted as
"$@", it preserves spaces within arguments - Expands to Multiple Values - Each argument becomes a separate value
- Best for Loops - Ideal for iterating through arguments
Example: How $@ Expands
If you run: ./script.sh arg1 arg2 arg3
Then:
$@expands to:arg1 arg2 arg3"$@"expands to:"arg1" "arg2" "arg3"(each as separate value)$*expands to:arg1 arg2 arg3(as single string)
Example 1: Demonstrating $@ Expansion
#!/bin/bash
# Script: show_at.sh
# Purpose: Show how $@ works
echo "Total arguments: $#"
echo ""
echo "Using \$@:"
echo "$@"
echo ""
echo "Looping through \$@:"
for arg in "$@"; do
echo " - $arg"
done
Usage:
$ ./show_at.sh apple banana cherry
Total arguments: 3
Using $@:
apple banana cherry
Looping through $@:
- apple
- banana
- cherry
Example 2: $@ with Spaces in Arguments
#!/bin/bash
# Script: spaces_demo.sh
# Purpose: Show how $@ handles spaces
echo "Arguments passed:"
for arg in "$@"; do
echo " [$arg]"
done
Usage:
$ ./spaces_demo.sh "first name" "last name" "city name"
Arguments passed:
[first name]
[last name]
[city name]
Why This Matters:
- Without quotes:
for arg in $@would split "first name" into "first" and "name" - With quotes:
for arg in "$@"keeps "first name" as one argument - Always use
"$@"for reliable argument processing
Example 3: Script Name and All Arguments
#!/bin/bash
# Script: info.sh
# Purpose: Display script info and argument count
echo "Script name: ${0}"
echo "Total arguments: $#"
echo "Arguments: $@"
Usage:
$ ./info.sh dgpro 25 "New York"
Script name: ./info.sh
Total arguments: 3
Arguments: dgpro 25 New York
#!/bin/bash
# Script: validate_args.sh
# Purpose: Validate number of arguments
if [ $# -lt 2 ]; then
echo "Error: At least 2 arguments required"
echo "Usage: $0 <name> <age>"
exit 1
fi
name=${1}
age=${2}
echo "Name: ${name}, Age: ${age}"
Usage:
$ ./validate_args.sh devopsgurupro
Error: At least 2 arguments required
Usage: ./validate_args.sh <name> <age>
$ ./validate_args.sh devopsgurupro 25
Name: devopsgurupro, Age: 25
π Difference Between $@ and $*
$@ vs $*
| Feature | $@ | $* |
|---|---|---|
| Quoting | Preserves individual arguments | Joins all arguments |
| Spaces | Handles spaces in arguments | May lose spaces |
| Looping | Better for loops | Less reliable |
| Usage | Recommended | Legacy |
Example: Demonstrating Difference
#!/bin/bash
# Script: args_demo.sh
# Purpose: Show difference between $@ and $*
echo "Using \$@:"
for arg in "$@"; do
echo " - $arg"
done
echo ""
echo "Using \$*:"
for arg in $*; do
echo " - $arg"
done
Usage:
$ ./args_demo.sh "first name" "second name" "third name"
Using $@:
- first name
- second name
- third name
Using $*:
- first
- name
- second
- name
- third
- name
π Processing Multiple Arguments
Example 1: Loop Through All Arguments
#!/bin/bash
# Script: process_args.sh
# Purpose: Process all arguments in a loop
echo "Processing $# arguments:"
for arg in "$@"; do
echo " Processing: $arg"
done
Usage:
$ ./process_args.sh file1.txt file2.txt file3.txt
Processing 3 arguments:
Processing: file1.txt
Processing: file2.txt
Processing: file3.txt
Example 2: Shift Arguments
#!/bin/bash
# Script: shift_args.sh
# Purpose: Demonstrate argument shifting
echo "First argument: $1"
shift
echo "After shift, first argument: $1"
shift
echo "After second shift, first argument: $1"
Usage:
$ ./shift_args.sh dgpro wahid sameer
First argument: dgpro
After shift, first argument: wahid
After second shift, first argument: sameer
π Complete Examples
Example 1: File Backup Script
#!/bin/bash
# Script: backup.sh
# Purpose: Backup files with command-line arguments
if [ $# -lt 1 ]; then
echo "Usage: $0 <file1> [file2] [file3] ..."
exit 1
fi
echo "Backing up $# files..."
for file in "$@"; do
if [ -f "$file" ]; then
cp "$file" "${file}.backup"
echo "β Backed up: $file"
else
echo "β File not found: $file"
fi
done
Usage:
$ ./backup.sh config.txt data.json script.sh
Backing up 3 files...
β Backed up: config.txt
β Backed up: data.json
β Backed up: script.sh
Example 2: User Information Script
#!/bin/bash
# Script: user_info.sh
# Purpose: Display user information from arguments
if [ $# -ne 3 ]; then
echo "Usage: $0 <name> <age> <city>"
exit 1
fi
name=$1
age=$2
city=$3
echo "=== User Information ==="
echo "Name: $name"
echo "Age: $age"
echo "City: $city"
Usage:
$ ./user_info.sh devopsgurupro 25 "New York"
=== User Information ===
Name: devopsgurupro
Age: 25
City: New York
Example 3: Calculator Script
#!/bin/bash
# Script: calculator.sh
# Purpose: Simple calculator using arguments
if [ $# -ne 3 ]; then
echo "Usage: $0 <number1> <operator> <number2>"
echo "Operators: +, -, *, /"
exit 1
fi
num1=$1
operator=$2
num2=$3
case $operator in
+)
result=$((num1 + num2))
;;
-)
result=$((num1 - num2))
;;
\*)
result=$((num1 * num2))
;;
/)
result=$((num1 / num2))
;;
*)
echo "Invalid operator"
exit 1
;;
esac
echo "$num1 $operator $num2 = $result"
Usage:
$ ./calculator.sh 10 + 5
10 + 5 = 15
$ ./calculator.sh 20 - 8
20 - 8 = 12
$ ./calculator.sh 6 \* 7
6 * 7 = 42
Example 4: Storing and Displaying Arguments
#!/bin/bash
# Script: country_info.sh
# Purpose: Store and display country arguments
echo "Your country name: $1 $2"
# Store all arguments in a variable
args="$@"
# Display arguments from the stored variable
echo "Stored arguments: ${args}"
# Display all arguments using $@
echo "All arguments: $@"
Usage:
$ ./country_info.sh United States
Your country name: United States
Stored arguments: United States
All arguments: United States
Explanation:
$1 $2- Accesses individual positional parametersargs="$@"- Stores all arguments in a variable${args}- Displays the stored arguments as a single string$@- Displays all arguments (same as the stored variable in this case)- This example shows different ways to access and display command-line arguments
β Best Practices
- Always validate the number of arguments using
$# - Use
"$@"instead of$*for better argument handling - Quote variables:
"${1}"to handle spaces properly - Provide usage information when arguments are missing
- Use meaningful variable names for clarity
- Check if arguments are files/directories before processing
- Use
shiftto process arguments sequentially - Document expected arguments in comments
- Provide helpful error messages
π Navigation
β¬ οΈ Previous: Reading User Input
π Current Location: Command-Line Arguments (You are here)
β‘οΈ Next Step: Command Output as Variable
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Positional Parameters: gnu.org/software/bash/manual/html_node/Positional-Parameters.html
- π Shell Scripting Guide: tldp.org/LDP/abs/html/special-chars.html
- π‘ Command-Line Arguments: linuxcommand.org
π Excellent! Command-Line Arguments Complete! π
CommandAsVariable
π Command Output as Variable
π Overview
π― Master Command Substitution and Output Assignment
This guide covers how to capture command output and store it in variables, enabling dynamic script behavior based on command results.
π What This Guide Covers
- π Command Substitution - Capturing command output
- π Syntax Methods - Backticks vs $() syntax
- π‘ Variable Assignment - Storing command results
- π Examples - Practical command substitution usage
- π― Use Cases - Real-world applications
- β Best Practices - Recommended approaches
π What is Command Substitution?
Command substitution allows you to capture the output of a command and use it as a value in your script. Instead of displaying output to the terminal, you can store it in a variable for later use or processing.
Key Characteristics:
- Executes a command and captures its output
- Stores output in a variable for reuse
- Enables dynamic script behavior
- Allows command chaining and processing
- Essential for automation and scripting
π Command Substitution Syntax
Method 1: Backtick Syntax (Legacy)
VARIABLE_NAME=`command_here`
Characteristics:
- Older syntax, still supported
- Can be harder to read with nested commands
- Less recommended for new scripts
Method 2: Dollar-Parenthesis Syntax (Recommended)
VARIABLE_NAME=$(command_here)
Characteristics:
- Modern, preferred syntax
- More readable and cleaner
- Easier to nest commands
- Better for complex operations
Comparison
| Feature | Backticks | $() |
|---|---|---|
| Readability | Less clear | More clear |
| Nesting | Difficult | Easy |
| Compatibility | Older shells | Modern shells |
| Recommendation | Legacy | Preferred |
π‘ Basic Command Substitution Examples
Example 1: Capturing Current Directory
#!/bin/bash
# Script: pwd_capture.sh
# Purpose: Capture current working directory
# Method 1: Using backticks
CURRENT_DIR_BACKTICK=`pwd`
# Method 2: Using $() - Recommended
CURRENT_DIR=$(pwd)
echo "Current Directory (backtick): ${CURRENT_DIR_BACKTICK}"
echo "Current Directory ($()): ${CURRENT_DIR}"
Output:
Current Directory (backtick): /home/devopsgurupro/projects
Current Directory ($()): /home/devopsgurupro/projects
Example 2: Capturing Date and Time
#!/bin/bash
# Script: datetime_capture.sh
# Purpose: Capture date and time information
# Capture current date
current_date=$(date +"%Y-%m-%d")
# Capture current time
current_time=$(date +"%H:%M:%S")
# Capture date and time together
date_time=$(date +"%D-%T")
echo "Date: ${current_date}"
echo "Time: ${current_time}"
echo "Date-Time: ${date_time}"
Output:
Date: 2024-01-15
Time: 14:30:45
Date-Time: 01/15/24-14:30:45
Example 3: Capturing User Information
#!/bin/bash
# Script: user_info_capture.sh
# Purpose: Capture user-related information
# Capture current user
current_user=$(whoami)
# Capture user ID
user_id=$(id -u)
# Capture home directory
home_dir=$(echo $HOME)
echo "Current User: ${current_user}"
echo "User ID: ${user_id}"
echo "Home Directory: ${home_dir}"
Output:
Current User: devopsgurupro
User ID: 1000
Home Directory: /home/devopsgurupro
π Practical Command Substitution Examples
Example 1: File Count and Size
#!/bin/bash
# Script: file_info.sh
# Purpose: Get file count and directory size
# Count files in current directory
file_count=$(ls -1 | wc -l)
# Get directory size
dir_size=$(du -sh . | cut -f1)
# Count subdirectories
subdir_count=$(find . -maxdepth 1 -type d | wc -l)
echo "Files in current directory: ${file_count}"
echo "Directory size: ${dir_size}"
echo "Subdirectories: ${subdir_count}"
Output:
Files in current directory: 15
Directory size: 2.5M
Subdirectories: 5
Example 2: System Information
#!/bin/bash
# Script: system_info.sh
# Purpose: Capture system information
# Get system uptime
uptime_info=$(uptime -p)
# Get available disk space
disk_space=$(df -h / | tail -1 | awk '{print $4}')
# Get memory usage
memory_usage=$(free -h | grep Mem | awk '{print $3}')
# Get CPU count
cpu_count=$(nproc)
echo "System Uptime: ${uptime_info}"
echo "Available Disk Space: ${disk_space}"
echo "Memory Usage: ${memory_usage}"
echo "CPU Count: ${cpu_count}"
Output:
System Uptime: up 5 days, 3 hours, 42 minutes
Available Disk Space: 45G
Memory Usage: 4.2G
CPU Count: 8
Example 3: Process Information
#!/bin/bash
# Script: process_info.sh
# Purpose: Capture process information
# Get process count
process_count=$(ps aux | wc -l)
# Get specific process PID
nginx_pid=$(pgrep nginx | head -1)
# Get running services count
service_count=$(systemctl list-units --type=service --state=running | wc -l)
echo "Total Processes: ${process_count}"
echo "Nginx PID: ${nginx_pid}"
echo "Running Services: ${service_count}"
Output:
Total Processes: 145
Nginx PID: 1234
Running Services: 8
Example 4: File Operations
#!/bin/bash
# Script: file_operations.sh
# Purpose: Perform file operations with command substitution
# Get list of files
files=$(ls -1 *.txt)
# Get file modification time
mod_time=$(stat -c %y myfile.txt)
# Get file permissions
permissions=$(stat -c %a myfile.txt)
# Get file size
file_size=$(wc -c < myfile.txt)
echo "Text Files:"
echo "${files}"
echo ""
echo "File: myfile.txt"
echo "Modification Time: ${mod_time}"
echo "Permissions: ${permissions}"
echo "Size: ${file_size} bytes"
Output:
Text Files:
file1.txt
file2.txt
file3.txt
File: myfile.txt
Modification Time: 2024-01-15 10:30:45.123456789 +0000
Permissions: 644
Size: 1024 bytes
π Nested Command Substitution
Example 1: Simple Nesting
#!/bin/bash
# Script: nested_commands.sh
# Purpose: Demonstrate nested command substitution
# Nested: Get current directory name
current_dir_name=$(basename $(pwd))
echo "Current Directory Name: ${current_dir_name}"
Output:
Current Directory Name: projects
Example 2: Complex Nesting
#!/bin/bash
# Script: complex_nesting.sh
# Purpose: Complex nested command substitution
# Get the size of the largest file in current directory
largest_file_size=$(ls -lS | head -2 | tail -1 | awk '{print $5}')
# Get the name of the largest file
largest_file_name=$(ls -lS | head -2 | tail -1 | awk '{print $NF}')
echo "Largest File: ${largest_file_name}"
echo "Size: ${largest_file_size} bytes"
Output:
Largest File: backup.tar.gz
Size: 524288000 bytes
π― Command Substitution with Variables
Example 1: Using Substituted Values
#!/bin/bash
# Script: use_substituted_values.sh
# Purpose: Use command substitution results in operations
# Capture current date
today=$(date +"%Y-%m-%d")
# Create filename with date
backup_file="backup_${today}.tar.gz"
# Create directory with date
backup_dir="backups_${today}"
echo "Backup File: ${backup_file}"
echo "Backup Directory: ${backup_dir}"
Output:
Backup File: backup_2024-01-15.tar.gz
Backup Directory: backups_2024-01-15
Example 2: Conditional Logic with Substitution
#!/bin/bash
# Script: conditional_substitution.sh
# Purpose: Use command substitution in conditionals
# Check if directory exists
dir_exists=$(test -d /tmp && echo "yes" || echo "no")
# Get current hour
current_hour=$(date +"%H")
# Check if it's morning (before 12)
is_morning=$([ $current_hour -lt 12 ] && echo "yes" || echo "no")
echo "Directory /tmp exists: ${dir_exists}"
echo "Is it morning: ${is_morning}"
Output:
Directory /tmp exists: yes
Is it morning: no
π Complete Real-World Examples
Example 1: Backup Script with Timestamps
#!/bin/bash
# Script: backup_with_timestamp.sh
# Purpose: Create timestamped backups
# Capture timestamp
timestamp=$(date +"%Y%m%d_%H%M%S")
# Create backup filename
backup_file="backup_${timestamp}.tar.gz"
# Create backup directory
backup_dir="backups_${timestamp}"
# Get current directory
source_dir=$(pwd)
echo "Creating backup..."
echo "Source: ${source_dir}"
echo "Backup File: ${backup_file}"
echo "Backup Directory: ${backup_dir}"
# Create directory
mkdir -p "${backup_dir}"
# Create backup (example)
tar -czf "${backup_dir}/${backup_file}" "${source_dir}"
echo "Backup completed successfully!"
Output:
Creating backup...
Source: /home/devopsgurupro/projects
Backup File: backup_20240115_143045.tar.gz
Backup Directory: backups_20240115_143045
Backup completed successfully!
Example 2: System Health Check
#!/bin/bash
# Script: health_check.sh
# Purpose: Check system health with command substitution
echo "=== System Health Check ==="
echo ""
# CPU Usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
echo "CPU Usage: ${cpu_usage}%"
# Memory Usage
memory_usage=$(free | grep Mem | awk '{printf("%.2f", $3/$2 * 100.0)}')
echo "Memory Usage: ${memory_usage}%"
# Disk Usage
disk_usage=$(df -h / | tail -1 | awk '{print $5}')
echo "Disk Usage: ${disk_usage}"
# Uptime
uptime_info=$(uptime -p)
echo "Uptime: ${uptime_info}"
# Load Average
load_avg=$(uptime | awk -F'load average:' '{print $2}')
echo "Load Average: ${load_avg}"
Output:
=== System Health Check ===
CPU Usage: 15.3%
Memory Usage: 42.15%
Disk Usage: 65%
Uptime: up 5 days, 3 hours, 42 minutes
Load Average: 0.45, 0.52, 0.48
Example 3: Log Analysis Script
#!/bin/bash
# Script: log_analysis.sh
# Purpose: Analyze logs using command substitution
log_file="/var/log/syslog"
# Count total lines
total_lines=$(wc -l < "${log_file}")
# Count errors
error_count=$(grep -i "error" "${log_file}" | wc -l)
# Count warnings
warning_count=$(grep -i "warning" "${log_file}" | wc -l)
# Get last entry
last_entry=$(tail -1 "${log_file}")
echo "=== Log Analysis ==="
echo "Log File: ${log_file}"
echo "Total Lines: ${total_lines}"
echo "Errors: ${error_count}"
echo "Warnings: ${warning_count}"
echo "Last Entry: ${last_entry}"
Output:
=== Log Analysis ===
Log File: /var/log/syslog
Total Lines: 5432
Errors: 23
Warnings: 156
Last Entry: Jan 15 14:30:45 server kernel: [12345.678901] Some kernel message
β Best Practices
- Always use
$()syntax instead of backticks for better readability - Quote variables:
"${variable}"to handle spaces and special characters - Use meaningful variable names that describe the captured data
- Test command substitution separately before using in scripts
- Handle errors gracefully when commands fail
- Avoid excessive nesting; break complex operations into steps
- Document what each command substitution captures
- Use
set -eto exit on command failures - Validate captured output before using it
- Consider performance impact of repeated command substitutions
π Navigation
β¬ οΈ Previous: Command-Line Arguments
π Current Location: Command Output as Variable (You are here)
β‘οΈ Next Step: Read-Only Variables
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output as Variable β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Command Substitution: gnu.org/software/bash/manual/html_node/Command-Substitution.html
- π Shell Scripting Guide: tldp.org/LDP/abs/html/commandsub.html
- π‘ Advanced Bash Scripting: tldp.org/LDP/abs/html/
π Excellent! Command Output as Variable Complete! π
ReadOnlyVariable
π Read-Only Variables
π Overview
π― Master Read-Only Variables in Shell Scripts
This guide covers how to create and use read-only variables to protect important values from accidental modification or deletion in shell scripts.
π What This Guide Covers
- π Read-Only Basics - Understanding immutable variables
- π Syntax - Creating read-only variables
- π‘οΈ Protection - Preventing variable modification
- π‘ Use Cases - When to use read-only variables
- π Examples - Practical read-only variable usage
- β Best Practices - Recommendations and patterns
π What are Read-Only Variables?
Read-only variables are variables that cannot be modified or unset after they are declared as read-only. Once a variable is marked as read-only, any attempt to change or delete it will result in an error. This is useful for protecting important configuration values and constants.
Key Characteristics:
- Cannot be modified after declaration
- Cannot be unset or deleted
- Useful for constants and configuration values
- Prevents accidental changes
- Improves script reliability and safety
π Read-Only Variable Syntax
Basic Syntax
readonly VARIABLE_NAME
Syntax with Assignment
readonly VARIABLE_NAME=value
Alternative Syntax
declare -r VARIABLE_NAME=value
π§ Creating Read-Only Variables
Method 1: Declare Then Make Read-Only
#!/bin/bash
# Script: readonly_method1.sh
# Purpose: Create read-only variable in two steps
# Declare and assign variable
name="devopsgurupro"
# Make it read-only
readonly name
echo "Name: ${name}"
Output:
Name: devopsgurupro
Method 2: Declare and Make Read-Only Together
#!/bin/bash
# Script: readonly_method2.sh
# Purpose: Create read-only variable in one step
# Declare and make read-only in one command
readonly APP_NAME="MyApplication"
readonly VERSION="1.0.0"
readonly PORT=8080
echo "Application: ${APP_NAME}"
echo "Version: ${VERSION}"
echo "Port: ${PORT}"
Output:
Application: MyApplication
Version: 1.0.0
Port: 8080
Method 3: Using declare -r
#!/bin/bash
# Script: readonly_method3.sh
# Purpose: Create read-only variable using declare
# Using declare -r (equivalent to readonly)
declare -r CONFIG_FILE="/etc/app/config.conf"
declare -r MAX_RETRIES=3
declare -r TIMEOUT=30
echo "Config File: ${CONFIG_FILE}"
echo "Max Retries: ${MAX_RETRIES}"
echo "Timeout: ${TIMEOUT}"
Output:
Config File: /etc/app/config.conf
Max Retries: 3
Timeout: 30
β οΈ Attempting to Modify Read-Only Variables
Example 1: Attempting to Modify
#!/bin/bash
# Script: readonly_error.sh
# Purpose: Demonstrate read-only protection
readonly name="devopsgurupro"
echo "Original name: ${name}"
# This will cause an error
name="newname"
echo "New name: ${name}"
Output:
Original name: devopsgurupro
./readonly_error.sh: line 7: name: readonly variable
Example 2: Attempting to Unset
#!/bin/bash
# Script: readonly_unset_error.sh
# Purpose: Demonstrate unset protection
readonly APP_VERSION="2.0.0"
echo "Version: ${APP_VERSION}"
# This will cause an error
unset APP_VERSION
echo "Version: ${APP_VERSION}"
Output:
Version: 2.0.0
./readonly_unset_error.sh: line 8: unset: APP_VERSION: cannot unset readonly variable
π Practical Read-Only Variable Examples
Example 1: Configuration Constants
#!/bin/bash
# Script: config_constants.sh
# Purpose: Define configuration as read-only variables
# Application Configuration
readonly APP_NAME="DevOpsApp"
readonly APP_VERSION="1.5.0"
readonly APP_AUTHOR="DevOps Team"
# Server Configuration
readonly SERVER_HOST="localhost"
readonly SERVER_PORT=8080
readonly SERVER_TIMEOUT=30
# Database Configuration
readonly DB_HOST="db.example.com"
readonly DB_PORT=5432
readonly DB_NAME="production"
echo "=== Application Configuration ==="
echo "App: ${APP_NAME} v${APP_VERSION}"
echo "Author: ${APP_AUTHOR}"
echo ""
echo "=== Server Configuration ==="
echo "Host: ${SERVER_HOST}:${SERVER_PORT}"
echo "Timeout: ${SERVER_TIMEOUT}s"
echo ""
echo "=== Database Configuration ==="
echo "Database: ${DB_NAME}@${DB_HOST}:${DB_PORT}"
Output:
=== Application Configuration ===
App: DevOpsApp v1.5.0
Author: DevOps Team
=== Server Configuration ===
Host: localhost:8080
Timeout: 30s
=== Database Configuration ===
Database: [email protected]:5432
Example 2: System Paths
#!/bin/bash
# Script: system_paths.sh
# Purpose: Define system paths as read-only
readonly LOG_DIR="/var/log/myapp"
readonly CONFIG_DIR="/etc/myapp"
readonly DATA_DIR="/var/lib/myapp"
readonly BACKUP_DIR="/backup/myapp"
echo "Log Directory: ${LOG_DIR}"
echo "Config Directory: ${CONFIG_DIR}"
echo "Data Directory: ${DATA_DIR}"
echo "Backup Directory: ${BACKUP_DIR}"
# Create directories if they don't exist
mkdir -p "${LOG_DIR}" "${CONFIG_DIR}" "${DATA_DIR}" "${BACKUP_DIR}"
echo "Directories created successfully"
Output:
Log Directory: /var/log/myapp
Config Directory: /etc/myapp
Data Directory: /var/lib/myapp
Backup Directory: /backup/myapp
Directories created successfully
Example 3: User Input with Read-Only
#!/bin/bash
# Script: readonly_user_input.sh
# Purpose: Accept user input and make it read-only
read -p "Enter your name: " user_name
readonly user_name
read -p "Enter your age: " user_age
readonly user_age
echo "Name: ${user_name}"
echo "Age: ${user_age}"
# This will cause an error
# user_name="newname"
Output:
Enter your name: devopsgurupro
Enter your age: 25
Name: devopsgurupro
Age: 25
Example 4: Listing Read-Only Variables
#!/bin/bash
# Script: list_readonly.sh
# Purpose: List all read-only variables
readonly VAR1="value1"
readonly VAR2="value2"
readonly VAR3="value3"
# List all read-only variables
echo "=== Read-Only Variables ==="
readonly -p
echo ""
echo "=== Custom Read-Only Variables ==="
readonly -p | grep "VAR"
Output:
=== Read-Only Variables ===
declare -r VAR1="value1"
declare -r VAR2="value2"
declare -r VAR3="value3"
...
=== Custom Read-Only Variables ===
declare -r VAR1="value1"
declare -r VAR2="value2"
declare -r VAR3="value3"
π― Use Cases for Read-Only Variables
1. Configuration Constants
readonly API_KEY="sk-1234567890abcdef"
readonly API_ENDPOINT="https://api.example.com"
readonly API_TIMEOUT=60
2. System Paths
readonly HOME_DIR="/home/user"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly LOG_FILE="${SCRIPT_DIR}/app.log"
3. Version Information
readonly SCRIPT_VERSION="2.1.0"
readonly SCRIPT_NAME="backup.sh"
readonly SCRIPT_AUTHOR="DevOps Team"
4. Limits and Thresholds
readonly MAX_RETRIES=5
readonly MAX_TIMEOUT=300
readonly MIN_DISK_SPACE=1000000000 # 1GB in bytes
5. Status Codes
readonly SUCCESS=0
readonly ERROR=1
readonly NOT_FOUND=2
readonly PERMISSION_DENIED=3
π Complete Real-World Example
#!/bin/bash
# Script: backup_with_readonly.sh
# Purpose: Backup script using read-only variables
# ============================================
# READ-ONLY CONFIGURATION
# ============================================
readonly SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_VERSION="1.0.0"
readonly BACKUP_DIR="/backup/data"
readonly SOURCE_DIR="/home/user/important"
readonly MAX_BACKUPS=5
readonly TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# Status codes
readonly SUCCESS=0
readonly ERROR=1
# ============================================
# FUNCTIONS
# ============================================
function log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
function create_backup() {
log_message "Starting backup..."
if [ ! -d "${SOURCE_DIR}" ]; then
log_message "Error: Source directory not found: ${SOURCE_DIR}"
return ${ERROR}
fi
mkdir -p "${BACKUP_DIR}"
local backup_file="${BACKUP_DIR}/backup_${TIMESTAMP}.tar.gz"
tar -czf "${backup_file}" "${SOURCE_DIR}"
if [ $? -eq 0 ]; then
log_message "Backup created: ${backup_file}"
return ${SUCCESS}
else
log_message "Error: Backup failed"
return ${ERROR}
fi
}
# ============================================
# MAIN SCRIPT
# ============================================
echo "=== ${SCRIPT_NAME} v${SCRIPT_VERSION} ==="
echo "Backup Directory: ${BACKUP_DIR}"
echo "Source Directory: ${SOURCE_DIR}"
echo "Max Backups: ${MAX_BACKUPS}"
echo ""
create_backup
exit $?
Output:
=== backup_with_readonly.sh v1.0.0 ===
Backup Directory: /backup/data
Source Directory: /home/user/important
Max Backups: 5
[2024-01-15 14:30:45] Starting backup...
[2024-01-15 14:30:47] Backup created: /backup/data/backup_20240115_143045.tar.gz
β Best Practices
- Use UPPERCASE names for read-only variables (convention)
- Define all read-only variables at the beginning of the script
- Use read-only for configuration values and constants
- Document the purpose of each read-only variable
- Use read-only for important paths and file locations
- Combine with command substitution for dynamic read-only values
- Use
readonly -pto list all read-only variables - Avoid making frequently changing values read-only
- Use meaningful names that indicate the variable is constant
- Group related read-only variables together
π Navigation
β¬ οΈ Previous: Command Output as Variable
π Current Location: Read-Only Variables (You are here)
β‘οΈ Next Step: String Conversion
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Readonly: gnu.org/software/bash/manual/html_node/Bash-Builtins.html
- π Shell Scripting Guide: tldp.org/LDP/abs/html/
- π‘ Variable Protection: linuxcommand.org
π Excellent! Read-Only Variables Complete! π
ConvertString
π€ String Conversion and Manipulation
π Overview
π― Master String Conversion and Manipulation in Shell Scripts
This guide covers how to convert strings between uppercase and lowercase, get string length, and perform various string manipulation operations.
π What This Guide Covers
- π€ Case Conversion - Converting between uppercase and lowercase
- π String Length - Getting the length of strings
- π String Manipulation - Various string operations
- π Examples - Practical string conversion usage
- π‘ Use Cases - Real-world applications
- β Best Practices - Recommendations and patterns
π€ What is String Conversion?
String conversion refers to transforming the case of characters in a string (uppercase to lowercase or vice versa) and manipulating string content. Bash provides parameter expansion operators that allow you to perform these operations efficiently without external commands.
Key Characteristics:
- Convert strings to uppercase or lowercase
- Get string length
- Manipulate string content
- Built-in Bash operators (no external commands needed)
- Efficient and fast operations
π String Conversion Syntax
Case Conversion Operators
| Operator | Description | Example |
|---|---|---|
${string^} | Convert first character to uppercase | ${string^} |
${string^^} | Convert all characters to uppercase | ${string^^} |
${string,} | Convert first character to lowercase | ${string,} |
${string,,} | Convert all characters to lowercase | ${string,,} |
${#string} | Get string length | ${#string} |
π€ Converting to Uppercase
Example 1: Convert First Character to Uppercase
#!/bin/bash
# Script: first_char_upper.sh
# Purpose: Convert first character to uppercase
string="my name is devopsgurupro"
echo "Original: ${string}"
echo "First char uppercase: ${string^}"
Output:
Original: my name is devopsgurupro
First char uppercase: My name is devopsgurupro
Example 2: Convert All Characters to Uppercase
#!/bin/bash
# Script: all_upper.sh
# Purpose: Convert entire string to uppercase
string="my name is devopsgurupro"
echo "Original: ${string}"
echo "All uppercase: ${string^^}"
Output:
Original: my name is devopsgurupro
All uppercase: MY NAME IS DEVOPSGURUPRO
Example 3: Multiple Strings to Uppercase
#!/bin/bash
# Script: multiple_upper.sh
# Purpose: Convert multiple strings to uppercase
name="john doe"
city="new york"
country="united states"
echo "Name: ${name^^}"
echo "City: ${city^^}"
echo "Country: ${country^^}"
Output:
Name: JOHN DOE
City: NEW YORK
Country: UNITED STATES
π‘ Converting to Lowercase
Example 1: Convert First Character to Lowercase
#!/bin/bash
# Script: first_char_lower.sh
# Purpose: Convert first character to lowercase
string="My name is DevOpsGuruPro"
echo "Original: ${string}"
echo "First char lowercase: ${string,}"
Output:
Original: My name is DevOpsGuruPro
First char lowercase: my name is DevOpsGuruPro
Example 2: Convert All Characters to Lowercase
#!/bin/bash
# Script: all_lower.sh
# Purpose: Convert entire string to lowercase
string="My name is DevOpsGuruPro"
echo "Original: ${string}"
echo "All lowercase: ${string,,}"
Output:
Original: My name is DevOpsGuruPro
All lowercase: my name is devopsgurupro
Example 3: Multiple Strings to Lowercase
#!/bin/bash
# Script: multiple_lower.sh
# Purpose: Convert multiple strings to lowercase
name="JOHN DOE"
city="NEW YORK"
country="UNITED STATES"
echo "Name: ${name,,}"
echo "City: ${city,,}"
echo "Country: ${country,,}"
Output:
Name: john doe
City: new york
Country: united states
π Getting String Length
Example 1: Basic String Length
#!/bin/bash
# Script: string_length.sh
# Purpose: Get length of strings
string="My name is DevOpsGuruPro"
echo "String: ${string}"
echo "Length: ${#string}"
Output:
String: My name is DevOpsGuruPro
Length: 25
Example 2: Multiple String Lengths
#!/bin/bash
# Script: multiple_lengths.sh
# Purpose: Get length of multiple strings
name="devopsgurupro"
email="[email protected]"
password="SecurePass123!"
echo "Name length: ${#name}"
echo "Email length: ${#email}"
echo "Password length: ${#password}"
Output:
Name length: 14
Email length: 18
Password length: 14
Example 3: String Length in Conditions
#!/bin/bash
# Script: length_validation.sh
# Purpose: Validate string length
read -p "Enter password: " -s password
echo ""
if [ ${#password} -lt 8 ]; then
echo "Error: Password must be at least 8 characters"
else
echo "Password accepted (${#password} characters)"
fi
Output:
Enter password:
Error: Password must be at least 8 characters
π Complete String Conversion Examples
Example 1: Comprehensive String Operations
#!/bin/bash
# Script: string_operations.sh
# Purpose: Demonstrate all string conversion operations
string="my name is devopsgurupro"
echo "=== Original String ==="
echo "String: ${string}"
echo "Length: ${#string}"
echo ""
echo "=== Uppercase Conversions ==="
echo "First char uppercase: ${string^}"
echo "All uppercase: ${string^^}"
echo ""
echo "=== Lowercase Conversions ==="
string2="My Name Is DevOpsGuruPro"
echo "Original: ${string2}"
echo "First char lowercase: ${string2,}"
echo "All lowercase: ${string2,,}"
Output:
=== Original String ===
String: my name is devopsgurupro
Length: 25
=== Uppercase Conversions ===
First char uppercase: My name is devopsgurupro
All uppercase: MY NAME IS DEVOPSGURUPRO
=== Lowercase Conversions ===
Original: My Name Is DevOpsGuruPro
First char lowercase: my Name Is DevOpsGuruPro
All lowercase: my name is devopsgurupro
Example 2: User Input Processing
#!/bin/bash
# Script: user_input_processing.sh
# Purpose: Process user input with case conversion
read -p "Enter your name: " name
read -p "Enter your city: " city
# Convert to proper case (first letter uppercase)
name="${name,,}" # Convert to lowercase first
name="${name^}" # Then convert first character to uppercase
city="${city,,}"
city="${city^}"
echo ""
echo "Name: ${name}"
echo "City: ${city}"
Output:
Enter your name: john doe
Enter your city: new york
Name: John doe
City: New york
Example 3: File Naming Convention
#!/bin/bash
# Script: file_naming.sh
# Purpose: Create files with standardized naming
read -p "Enter project name: " project_name
# Convert to lowercase and replace spaces with underscores
project_name="${project_name,,}"
project_name="${project_name// /_}"
# Create files
config_file="${project_name}_config.conf"
log_file="${project_name}_$(date +%Y%m%d).log"
backup_file="${project_name}_backup_$(date +%Y%m%d_%H%M%S).tar.gz"
echo "Config file: ${config_file}"
echo "Log file: ${log_file}"
echo "Backup file: ${backup_file}"
Output:
Enter project name: My DevOps Project
Config file: my_devops_project_config.conf
Log file: my_devops_project_20240115.log
Backup file: my_devops_project_backup_20240115_143045.tar.gz
Example 4: String Validation
#!/bin/bash
# Script: string_validation.sh
# Purpose: Validate strings using conversion
read -p "Enter username: " username
# Check length
if [ ${#username} -lt 3 ]; then
echo "Error: Username must be at least 3 characters"
exit 1
fi
if [ ${#username} -gt 20 ]; then
echo "Error: Username cannot exceed 20 characters"
exit 1
fi
# Convert to lowercase for consistency
username="${username,,}"
echo "Username accepted: ${username}"
Output:
Enter username: JohnDoe
Username accepted: johndoe
Example 5: Log Message Formatting
#!/bin/bash
# Script: log_formatter.sh
# Purpose: Format log messages with case conversion
log_level="warning"
message="system memory usage is high"
# Convert log level to uppercase
log_level="${log_level^^}"
# Convert message first letter to uppercase
message="${message^}"
timestamp=$(date +"%Y-%m-%d %H:%M:%S")
echo "[${timestamp}] ${log_level}: ${message}"
Output:
[2024-01-15 14:30:45] WARNING: System memory usage is high
π― Practical Use Cases
1. Username Normalization
read -p "Enter username: " username
username="${username,,}" # Convert to lowercase
2. File Extension Handling
filename="MyDocument.PDF"
extension="${filename##*.}"
extension="${extension,,}" # Convert to lowercase
3. Environment Variable Validation
env_value="Production"
env_value="${env_value,,}" # Normalize to lowercase
4. Log Level Formatting
level="info"
level="${level^^}" # Convert to uppercase for display
5. Password Strength Checking
password="MyPassword123"
if [ ${#password} -ge 8 ]; then
echo "Strong password"
fi
β Best Practices
- Use
${string,,}for lowercase and${string^^}for uppercase - Always quote variables:
"${string}"to handle spaces - Use string length validation for user input
- Normalize user input (convert to lowercase) for consistency
- Use uppercase for constants and environment variables
- Combine case conversion with other string operations
- Test string operations with various inputs
- Document the purpose of string conversions
- Use meaningful variable names
- Consider performance for large strings
π Navigation
β¬ οΈ Previous: Read-Only Variables
π Current Location: String Conversion and Manipulation (You are here)
β‘οΈ Next Step: Substring Operations
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Parameter Expansion: gnu.org/software/bash/manual/html_node/Parameter-Expansion.html
- π String Manipulation Guide: tldp.org/LDP/abs/html/string-manipulation.html
- π‘ Advanced Bash Scripting: tldp.org/LDP/abs/html/
π Excellent! String Conversion Complete! π
SubString
π Substring Operations
π Overview
π― Master Substring Operations in Shell Scripts
This guide covers extracting substrings, pattern matching, and string replacement operations using Bash parameter expansion.
π What This Guide Covers
- π Substring Extraction - Getting parts of strings
- π Position-Based Extraction - Using offsets and lengths
- π€ Pattern Matching - Matching and removing patterns
- π String Replacement - Replacing text in strings
- π Examples - Practical substring operations
- β Best Practices - Recommendations and patterns
π What are Substring Operations?
Substring operations allow you to extract, manipulate, and replace portions of strings. Bash provides powerful parameter expansion operators for these operations without needing external commands like sed or awk.
Key Characteristics:
- Extract parts of strings by position
- Match and remove patterns
- Replace text within strings
- Built-in Bash operators (efficient)
- Support for both shortest and longest matches
π Substring Operation Syntax
Substring Extraction Operators
| Operator | Description | Example |
|---|---|---|
${string:position} | Extract from position to end | ${string:4} |
${string:position:length} | Extract substring with length | ${string:0:3} |
${string: -n} | Extract last n characters | ${string: -3} |
${string#pattern} | Remove shortest match from start | ${string#a*c} |
${string##pattern} | Remove longest match from start | ${string##a*c} |
${string%pattern} | Remove shortest match from end | ${string%b*z} |
${string%%pattern} | Remove longest match from end | ${string%%b*z} |
${string/pattern/replacement} | Replace first occurrence | ${string/abc/xyz} |
${string//pattern/replacement} | Replace all occurrences | ${string//abc/xyz} |
π Extracting Substrings by Position
Example 1: Extract from Position to End
#!/bin/bash
# Script: substring_position.sh
# Purpose: Extract substring from specific position
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "From position 0: ${string:0}"
echo "From position 1: ${string:1}"
echo "From position 4: ${string:4}"
echo "From position 10: ${string:10}"
Output:
Original string: abcdevopsguruproabcxyz
From position 0: abcdevopsguruproabcxyz
From position 1: bcdevopsguruproabcxyz
From position 4: devopsguruproabcxyz
From position 10: bcxyz
Example 2: Extract with Specific Length
#!/bin/bash
# Script: substring_length.sh
# Purpose: Extract substring with specific length
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Position 0, length 3: ${string:0:3}"
echo "Position 3, length 3: ${string:3:3}"
echo "Position 6, length 6: ${string:6:6}"
echo "Position 10, length 5: ${string:10:5}"
Output:
Original string: abcdevopsguruproabcxyz
Position 0, length 3: abc
Position 3, length 3: dev
Position 6, length 6: ravab
Position 10, length 5: bcxyz
Example 3: Extract Last N Characters
#!/bin/bash
# Script: substring_last.sh
# Purpose: Extract last n characters from string
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Last 1 character: ${string: -1}"
echo "Last 3 characters: ${string: -3}"
echo "Last 5 characters: ${string: -5}"
echo "Last 10 characters: ${string: -10}"
Output:
Original string: abcdevopsguruproabcxyz
Last 1 character: z
Last 3 characters: xyz
Last 5 characters: bcxyz
Last 10 characters: ruproabcxyz
π€ Pattern Matching and Removal
Example 1: Remove Shortest Match from Start
#!/bin/bash
# Script: pattern_shortest_start.sh
# Purpose: Remove shortest pattern match from start
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Remove a*c (shortest): ${string#a*c}"
echo "Remove a*v (shortest): ${string#a*v}"
Output:
Original string: abcdevopsguruproabcxyz
Remove a*c (shortest): devopsguruproabcxyz
Remove a*v (shortest): abcxyz
Example 2: Remove Longest Match from Start
#!/bin/bash
# Script: pattern_longest_start.sh
# Purpose: Remove longest pattern match from start
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Remove a*c (longest): ${string##a*c}"
echo "Remove a*v (longest): ${string##a*v}"
Output:
Original string: abcdevopsguruproabcxyz
Remove a*c (longest): xyz
Remove a*v (longest): xyz
Example 3: Remove Shortest Match from End
#!/bin/bash
# Script: pattern_shortest_end.sh
# Purpose: Remove shortest pattern match from end
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Remove b*z (shortest): ${string%b*z}"
echo "Remove a*z (shortest): ${string%a*z}"
Output:
Original string: abcdevopsguruproabcxyz
Remove b*z (shortest): abcdevopsgurupro
Remove a*z (shortest): abcdevopsguruproabcxyz
Example 4: Remove Longest Match from End
#!/bin/bash
# Script: pattern_longest_end.sh
# Purpose: Remove longest pattern match from end
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Remove b*z (longest): ${string%%b*z}"
echo "Remove a*z (longest): ${string%%a*z}"
Output:
Original string: abcdevopsguruproabcxyz
Remove b*z (longest): abcdevopsgurupro
Remove a*z (longest): (empty)
π String Replacement
Example 1: Replace First Occurrence
#!/bin/bash
# Script: replace_first.sh
# Purpose: Replace first occurrence of pattern
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Replace abc with xyz: ${string/abc/xyz}"
echo "Replace a with X: ${string/a/X}"
echo "Replace devopsgurupro with DEVOPSGURUPRO: ${string/devopsgurupro/DEVOPSGURUPRO}"
Output:
Original string: abcdevopsguruproabcxyz
Replace abc with xyz: xyzdevopsguruproabcxyz
Replace a with X: XbcdevopsguruproXbcXyz
Replace devopsgurupro with DEVOPSGURUPRO: abcDEVOPSGURUPROabcxyz
Example 2: Replace All Occurrences
#!/bin/bash
# Script: replace_all.sh
# Purpose: Replace all occurrences of pattern
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Replace abc with xyz: ${string//abc/xyz}"
echo "Replace a with X: ${string//a/X}"
echo "Replace devopsgurupro with DEVOPSGURUPRO: ${string//devopsgurupro/DEVOPSGURUPRO}"
Output:
Original string: abcdevopsguruproabcxyz
Replace abc with xyz: xyzdevopsgurupoxyzxyz
Replace a with X: XbcdevopsguruproXbcXyz
Replace devopsgurupro with DEVOPSGURUPRO: abcDEVOPSGURUPROabcxyz
Example 3: Remove First Occurrence
#!/bin/bash
# Script: remove_first.sh
# Purpose: Remove first occurrence of pattern
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Remove abc: ${string/abc}"
echo "Remove devopsgurupro: ${string/devopsgurupro}"
echo "Remove a: ${string/a}"
Output:
Original string: abcdevopsguruproabcxyz
Remove abc: devopsguruproabcxyz
Remove devopsgurupro: abcabcxyz
Remove a: bcdevopsguruproabcxyz
Example 4: Remove All Occurrences
#!/bin/bash
# Script: remove_all.sh
# Purpose: Remove all occurrences of pattern
string="abcdevopsguruproabcxyz"
echo "Original string: ${string}"
echo "Remove abc: ${string//abc}"
echo "Remove a: ${string//a}"
echo "Remove devopsgurupro: ${string//devopsgurupro}"
Output:
Original string: abcdevopsguruproabcxyz
Remove abc: devopsgurupoxyz
Remove a: bcdevopsgurupobcxyz
Remove devopsgurupro: abcabcxyz
π Complete Substring Examples
Example 1: File Path Manipulation
#!/bin/bash
# Script: file_path_manipulation.sh
# Purpose: Extract parts of file paths
filepath="/home/user/documents/myfile.txt"
echo "Full path: ${filepath}"
echo "Filename: ${filepath##*/}"
echo "Directory: ${filepath%/*}"
echo "Extension: ${filepath##*.}"
echo "Filename without extension: ${filepath%.*}"
Output:
Full path: /home/user/documents/myfile.txt
Filename: myfile.txt
Directory: /home/user/documents
Extension: txt
Filename without extension: /home/user/documents/myfile
Example 2: URL Parsing
#!/bin/bash
# Script: url_parsing.sh
# Purpose: Parse URL components
url="https://www.example.com:8080/path/to/page?query=value#section"
echo "Full URL: ${url}"
echo "Protocol: ${url%%://*}"
echo "Domain: ${url#*://}"
echo "Domain only: ${url#*://}"
echo "Domain only: ${domain%/*}"
Output:
Full URL: https://www.example.com:8080/path/to/page?query=value#section
Protocol: https
Domain: www.example.com:8080/path/to/page?query=value#section
Example 3: Email Validation and Parsing
#!/bin/bash
# Script: email_parsing.sh
# Purpose: Parse email address
email="[email protected]"
echo "Email: ${email}"
echo "Username: ${email%@*}"
echo "Domain: ${email#*@}"
Output:
Email: [email protected]
Username: user
Domain: example.com
Example 4: Version String Parsing
#!/bin/bash
# Script: version_parsing.sh
# Purpose: Parse version strings
version="2.5.3-beta"
echo "Full version: ${version}"
echo "Major version: ${version%%.*}"
echo "Without beta: ${version%-*}"
echo "Beta part: ${version#*-}"
Output:
Full version: 2.5.3-beta
Major version: 2
Without beta: 2.5.3
Beta part: beta
Example 5: String Cleanup
#!/bin/bash
# Script: string_cleanup.sh
# Purpose: Clean up strings
text=" hello world "
echo "Original: [${text}]"
echo "Remove leading spaces: [${text#*( )}]"
echo "Remove trailing spaces: [${text%*( )}]"
# Remove all spaces
text_no_spaces="${text// }"
echo "Remove all spaces: [${text_no_spaces}]"
Output:
Original: [ hello world ]
Remove all spaces: [helloworld]
π― Practical Use Cases
1. Extract File Extension
filename="document.pdf"
extension="${filename##*.}"
2. Get Directory from Path
filepath="/home/user/file.txt"
directory="${filepath%/*}"
3. Remove File Extension
filename="archive.tar.gz"
name="${filename%.*}"
4. Extract Domain from Email
email="[email protected]"
domain="${email#*@}"
5. Parse Version Numbers
version="1.2.3"
major="${version%%.*}"
β Best Practices
- Always quote variables:
"${string}"to handle spaces - Use
${string:position:length}for position-based extraction - Use
#and##for removing from the start - Use
%and%%for removing from the end - Use
/for replacing first occurrence - Use
//for replacing all occurrences - Test substring operations with various inputs
- Document complex substring operations
- Consider using
sedorawkfor very complex operations - Use meaningful variable names
π Navigation
β¬ οΈ Previous: String Conversion
π Current Location: Substring Operations (You are here)
β‘οΈ Next Step: Default Values
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Parameter Expansion: gnu.org/software/bash/manual/html_node/Parameter-Expansion.html
- π String Manipulation Guide: tldp.org/LDP/abs/html/string-manipulation.html
- π‘ Advanced Bash Scripting: tldp.org/LDP/abs/html/
π Excellent! Substring Operations Complete! π
DefaultValue
π― Default Values and Parameter Expansion
π Overview
π― Master Default Values and Parameter Expansion in Shell Scripts
This guide covers how to set default values for variables, handle unset variables, and validate parameters using Bash parameter expansion.
π What This Guide Covers
- π― Default Values - Setting fallback values for variables
- π Parameter Expansion - Using expansion operators
- β Validation - Checking if variables are set
- π‘ Use Cases - Practical applications
- π Examples - Real-world scenarios
- β Best Practices - Recommendations and patterns
π― What are Default Values?
Default values allow you to provide fallback values when variables are unset or null. This is useful for handling optional parameters, providing sensible defaults, and making scripts more robust and user-friendly.
Key Characteristics:
- Provide fallback values for unset variables
- Handle null or empty variables
- Improve script robustness
- Reduce error handling code
- Make scripts more flexible
π Default Value Syntax
Default Value Operators
| Operator | Description | Example |
|---|---|---|
${parameter:-word} | Use default if unset or null | ${name:-Guest} |
${parameter-word} | Use default if unset (not null) | ${name-Guest} |
${parameter:=word} | Assign default if unset or null | ${name:=Guest} |
${parameter=word} | Assign default if unset (not null) | ${name=Guest} |
${parameter:?word} | Error if unset or null | ${name:?Name required} |
${parameter?word} | Error if unset (not null) | ${name?Name required} |
${parameter:+word} | Use word if set and not null | ${name:+Hello $name} |
${parameter+word} | Use word if set (even if null) | ${name+Hello $name} |
π― Using Default Values
Example 1: Default if Unset or Null (:-)
#!/bin/bash
# Script: default_unset_null.sh
# Purpose: Use default if variable is unset or null
# Unset variable
echo "Unset variable: ${unset_var:-World}"
# Null variable
null_var=""
echo "Null variable: ${null_var:-World}"
# Set variable
set_var="DevOps"
echo "Set variable: ${set_var:-World}"
Output:
Unset variable: World
Null variable: World
Set variable: DevOps
Example 2: Default if Unset Only (-)
#!/bin/bash
# Script: default_unset_only.sh
# Purpose: Use default if variable is unset (not null)
# Unset variable
echo "Unset variable: ${unset_var-World}"
# Null variable (empty string)
null_var=""
echo "Null variable: ${null_var-World}"
# Set variable
set_var="DevOps"
echo "Set variable: ${set_var-World}"
Output:
Unset variable: World
Null variable:
Set variable: DevOps
Example 3: Assign Default if Unset or Null (:=)
#!/bin/bash
# Script: assign_default_unset_null.sh
# Purpose: Assign default if variable is unset or null
# Unset variable - will be assigned
echo "Before: ${unset_var:=DefaultValue}"
echo "After: ${unset_var}"
# Null variable - will be assigned
null_var=""
echo "Before: ${null_var:=DefaultValue}"
echo "After: ${null_var}"
Output:
Before: DefaultValue
After: DefaultValue
Before: DefaultValue
After: DefaultValue
Example 4: Assign Default if Unset Only (=)
#!/bin/bash
# Script: assign_default_unset_only.sh
# Purpose: Assign default if variable is unset (not null)
# Unset variable - will be assigned
echo "Before: ${unset_var=DefaultValue}"
echo "After: ${unset_var}"
# Null variable - will NOT be assigned
null_var=""
echo "Before: ${null_var=DefaultValue}"
echo "After: ${null_var}"
Output:
Before: DefaultValue
After: DefaultValue
Before:
After:
β Variable Validation
Example 1: Error if Unset or Null (:?)
#!/bin/bash
# Script: error_unset_null.sh
# Purpose: Display error if variable is unset or null
# This will cause an error
: ${required_var:?"Error: required_var must be set"}
echo "Script continues..."
Usage:
$ ./error_unset_null.sh
./error_unset_null.sh: line 5: required_var: Error: required_var must be set
$ required_var="value" ./error_unset_null.sh
Script continues...
Example 2: Error if Unset Only (?)
#!/bin/bash
# Script: error_unset_only.sh
# Purpose: Display error if variable is unset (not null)
# This will cause an error if unset
: ${required_var?"Error: required_var must be set"}
echo "Script continues..."
Usage:
$ ./error_unset_only.sh
./error_unset_only.sh: line 5: required_var: Error: required_var must be set
$ required_var="" ./error_unset_only.sh
Script continues...
Example 3: Validate Command-Line Arguments
#!/bin/bash
# Script: validate_arguments.sh
# Purpose: Validate command-line arguments
# Validate first argument
: ${1:?"Usage: $0 <name> [age]"}
name="$1"
age="${2:-Unknown}"
echo "Name: ${name}"
echo "Age: ${age}"
Usage:
$ ./validate_arguments.sh
./validate_arguments.sh: line 5: 1: Usage: ./validate_arguments.sh <name> [age]
$ ./validate_arguments.sh John
Name: John
Age: Unknown
$ ./validate_arguments.sh John 25
Name: John
Age: 25
π Conditional Value Expansion
Example 1: Use Value if Set and Not Null (:+)
#!/bin/bash
# Script: use_if_set_not_null.sh
# Purpose: Use value if set and not null
# Unset variable
echo "Unset: ${unset_var:+Value is set}"
# Null variable
null_var=""
echo "Null: ${null_var:+Value is set}"
# Set variable
set_var="DevOps"
echo "Set: ${set_var:+Value is set}"
Output:
Unset:
Null:
Set: Value is set
Example 2: Use Value if Set (+)
#!/bin/bash
# Script: use_if_set.sh
# Purpose: Use value if set (even if null)
# Unset variable
echo "Unset: ${unset_var+Value is set}"
# Null variable
null_var=""
echo "Null: ${null_var+Value is set}"
# Set variable
set_var="DevOps"
echo "Set: ${set_var+Value is set}"
Output:
Unset:
Null: Value is set
Set: Value is set
π Practical Default Value Examples
Example 1: User Input with Defaults
#!/bin/bash
# Script: user_input_defaults.sh
# Purpose: Accept user input with default values
read -p "Enter your name (default: Guest): " name
name="${name:-Guest}"
read -p "Enter your age (default: Unknown): " age
age="${age:-Unknown}"
read -p "Enter your city (default: Not specified): " city
city="${city:-Not specified}"
echo ""
echo "=== User Information ==="
echo "Name: ${name}"
echo "Age: ${age}"
echo "City: ${city}"
Output:
Enter your name (default: Guest):
Enter your age (default: Unknown): 25
Enter your city (default: Not specified):
=== User Information ===
Name: Guest
Age: 25
City: Not specified
Example 2: Configuration with Defaults
#!/bin/bash
# Script: config_defaults.sh
# Purpose: Configuration with default values
# Environment variables with defaults
APP_NAME="${APP_NAME:-MyApplication}"
APP_PORT="${APP_PORT:-8080}"
APP_HOST="${APP_HOST:-localhost}"
LOG_LEVEL="${LOG_LEVEL:-INFO}"
DEBUG_MODE="${DEBUG_MODE:-false}"
echo "=== Application Configuration ==="
echo "App Name: ${APP_NAME}"
echo "Port: ${APP_PORT}"
echo "Host: ${APP_HOST}"
echo "Log Level: ${LOG_LEVEL}"
echo "Debug Mode: ${DEBUG_MODE}"
Usage:
$ ./config_defaults.sh
=== Application Configuration ===
App Name: MyApplication
Port: 8080
Host: localhost
Log Level: INFO
Debug Mode: false
$ APP_NAME="CustomApp" APP_PORT=9000 ./config_defaults.sh
=== Application Configuration ===
App Name: CustomApp
Port: 9000
Host: localhost
Log Level: INFO
Debug Mode: false
Example 3: Function Parameters with Defaults
#!/bin/bash
# Script: function_defaults.sh
# Purpose: Function parameters with defaults
function greet() {
local name="${1:-Friend}"
local greeting="${2:-Hello}"
echo "${greeting}, ${name}!"
}
greet
greet "John"
greet "Jane" "Hi"
Output:
Hello, Friend!
Hello, John!
Hi, Jane!
Example 4: File Path Defaults
#!/bin/bash
# Script: file_path_defaults.sh
# Purpose: File paths with defaults
# Get script directory
SCRIPT_DIR="${SCRIPT_DIR:-.}"
# Get config file
CONFIG_FILE="${CONFIG_FILE:-${SCRIPT_DIR}/config.conf}"
# Get log file
LOG_FILE="${LOG_FILE:-${SCRIPT_DIR}/app.log}"
# Get data directory
DATA_DIR="${DATA_DIR:-${SCRIPT_DIR}/data}"
echo "Script Directory: ${SCRIPT_DIR}"
echo "Config File: ${CONFIG_FILE}"
echo "Log File: ${LOG_FILE}"
echo "Data Directory: ${DATA_DIR}"
Output:
Script Directory: .
Config File: ./config.conf
Log File: ./app.log
Data Directory: ./data
Example 5: Complete Application Setup
#!/bin/bash
# Script: app_setup.sh
# Purpose: Complete application setup with defaults
# Validate required parameters
: ${1:?"Usage: $0 <app_name> [environment]"}
APP_NAME="$1"
ENVIRONMENT="${2:-development}"
# Set defaults based on environment
if [ "${ENVIRONMENT}" = "production" ]; then
APP_PORT="${APP_PORT:-443}"
LOG_LEVEL="${LOG_LEVEL:-ERROR}"
DEBUG_MODE="${DEBUG_MODE:-false}"
else
APP_PORT="${APP_PORT:-8080}"
LOG_LEVEL="${LOG_LEVEL:-DEBUG}"
DEBUG_MODE="${DEBUG_MODE:-true}"
fi
echo "=== Application Setup ==="
echo "App Name: ${APP_NAME}"
echo "Environment: ${ENVIRONMENT}"
echo "Port: ${APP_PORT}"
echo "Log Level: ${LOG_LEVEL}"
echo "Debug Mode: ${DEBUG_MODE}"
Usage:
$ ./app_setup.sh
./app_setup.sh: line 6: 1: Usage: ./app_setup.sh <app_name> [environment]
$ ./app_setup.sh MyApp
=== Application Setup ===
App Name: MyApp
Environment: development
Port: 8080
Log Level: DEBUG
Debug Mode: true
$ ./app_setup.sh MyApp production
=== Application Setup ===
App Name: MyApp
Environment: production
Port: 443
Log Level: ERROR
Debug Mode: false
π― Use Cases for Default Values
1. Optional Command-Line Arguments
name="${1:-Guest}"
age="${2:-Unknown}"
2. Environment Variables
PORT="${PORT:-8080}"
HOST="${HOST:-localhost}"
3. Configuration Files
CONFIG_FILE="${CONFIG_FILE:-/etc/app/config.conf}"
4. Temporary Directories
TEMP_DIR="${TEMP_DIR:-/tmp}"
5. User Preferences
EDITOR="${EDITOR:-nano}"
SHELL="${SHELL:-/bin/bash}"
β Best Practices
- Use
${var:-default}for optional parameters - Use
${var:?error}to validate required parameters - Use
${var:=default}to assign and use defaults - Always quote variables:
"${var:-default}" - Document default values in comments
- Use meaningful default values
- Validate critical parameters early in scripts
- Use environment variables for configuration
- Combine with command substitution for dynamic defaults
- Test scripts with and without parameters
π Navigation
β¬ οΈ Previous: Substring Operations
π Current Location: Default Values and Parameter Expansion (You are here)
β‘οΈ Next Step: Arithmetic Operations
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Parameter Expansion: gnu.org/software/bash/manual/html_node/Parameter-Expansion.html
- π Shell Scripting Guide: tldp.org/LDP/abs/html/parameter-substitution.html
- π‘ Advanced Bash Scripting: tldp.org/LDP/abs/html/
π Excellent! Default Values Complete! π
ArithmeticOperation
π’ Arithmetic Operations
π Overview
π― Master Arithmetic Operations in Shell Scripts
This guide covers performing mathematical calculations in Bash using various methods including double parentheses, let command, and expr command.
π What This Guide Covers
- π’ Arithmetic Basics - Understanding math operations
- π§ Methods - Different ways to perform calculations
- β Operators - Addition, subtraction, multiplication, division
- π Examples - Practical arithmetic usage
- π― Use Cases - Real-world applications
- β Best Practices - Recommendations and patterns
π’ What are Arithmetic Operations?
Arithmetic operations allow you to perform mathematical calculations in shell scripts. Bash provides multiple methods to perform calculations, each with different syntax and capabilities. These operations are essential for counters, calculations, and numeric comparisons.
Key Characteristics:
- Perform mathematical calculations
- Support basic arithmetic operators
- Multiple methods available
- Integer arithmetic (no floating-point by default)
- Essential for loops and counters
π Arithmetic Methods
Available Methods
| Method | Syntax | Recommended | Notes |
|---|---|---|---|
| Double Parenthesis | $((expression)) | β Yes | Modern, recommended |
| Let Command | let "expression" | β οΈ Legacy | Still works, older syntax |
| Expr Command | expr $a + $b | β οΈ Legacy | External command, slower |
π§ Method 1: Double Parenthesis (Recommended)
Syntax
result=$((expression))
Basic Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
+ | Addition | $((10 + 5)) = 15 |
- | Subtraction | $((10 - 5)) = 5 |
* | Multiplication | $((10 * 5)) = 50 |
/ | Division | $((10 / 5)) = 2 |
% | Modulo (remainder) | $((10 % 3)) = 1 |
** | Exponentiation | $((2 ** 3)) = 8 |
Example 1: Basic Arithmetic Operations
#!/bin/bash
# Script: basic_arithmetic.sh
# Purpose: Demonstrate basic arithmetic operations
a=20
b=5
echo "=== Basic Arithmetic Operations ==="
echo "a = ${a}, b = ${b}"
echo ""
# Addition
sum=$((a + b))
echo "Addition: ${a} + ${b} = ${sum}"
# Subtraction
diff=$((a - b))
echo "Subtraction: ${a} - ${b} = ${diff}"
# Multiplication
product=$((a * b))
echo "Multiplication: ${a} * ${b} = ${product}"
# Division
quotient=$((a / b))
echo "Division: ${a} / ${b} = ${quotient}"
# Modulo
remainder=$((a % b))
echo "Modulo: ${a} % ${b} = ${remainder}"
# Exponentiation
power=$((2 ** 3))
echo "Exponentiation: 2 ** 3 = ${power}"
Output:
=== Basic Arithmetic Operations ===
a = 20, b = 5
Addition: 20 + 5 = 25
Subtraction: 20 - 5 = 15
Multiplication: 20 * 5 = 100
Division: 20 / 5 = 4
Modulo: 20 % 5 = 0
Exponentiation: 2 ** 3 = 8
Example 2: Increment and Decrement
#!/bin/bash
# Script: increment_decrement.sh
# Purpose: Demonstrate increment and decrement operations
a=5
echo "Initial value: a = ${a}"
echo ""
# Post-increment
echo "Post-increment: a++ = $((a++))"
echo "After post-increment: a = ${a}"
echo ""
# Pre-increment
echo "Pre-increment: ++a = $((++a))"
echo "After pre-increment: a = ${a}"
echo ""
# Post-decrement
echo "Post-decrement: a-- = $((a--))"
echo "After post-decrement: a = ${a}"
echo ""
# Pre-decrement
echo "Pre-decrement: --a = $((--a))"
echo "After pre-decrement: a = ${a}"
Output:
Initial value: a = 5
Post-increment: a++ = 5
After post-increment: a = 6
Pre-increment: ++a = 7
After pre-increment: a = 7
Post-decrement: a-- = 7
After post-decrement: a = 6
Pre-decrement: --a = 5
After pre-decrement: a = 5
Example 3: Compound Assignment Operators
#!/bin/bash
# Script: compound_assignment.sh
# Purpose: Demonstrate compound assignment operators
a=10
echo "Initial value: a = ${a}"
echo ""
# Addition assignment
((a += 5))
echo "After a += 5: a = ${a}"
# Subtraction assignment
((a -= 3))
echo "After a -= 3: a = ${a}"
# Multiplication assignment
((a *= 2))
echo "After a *= 2: a = ${a}"
# Division assignment
((a /= 4))
echo "After a /= 4: a = ${a}"
# Modulo assignment
((a %= 5))
echo "After a %= 5: a = ${a}"
Output:
Initial value: a = 10
After a += 5: a = 15
After a -= 3: a = 12
After a *= 2: a = 24
After a /= 4: a = 6
After a %= 5: a = 1
Example 4: Complex Expressions
#!/bin/bash
# Script: complex_expressions.sh
# Purpose: Demonstrate complex arithmetic expressions
a=10
b=3
c=2
echo "a = ${a}, b = ${b}, c = ${c}"
echo ""
# Complex expression
result=$((a + b * c))
echo "a + b * c = ${a} + ${b} * ${c} = ${result}"
# With parentheses
result=$(((a + b) * c))
echo "(a + b) * c = (${a} + ${b}) * ${c} = ${result}"
# Multiple operations
result=$((a * b + c - 5))
echo "a * b + c - 5 = ${a} * ${b} + ${c} - 5 = ${result}"
# Using variables in expressions
result=$((a ** b % c))
echo "a ** b % c = ${a} ** ${b} % ${c} = ${result}"
Output:
a = 10, b = 3, c = 2
a + b * c = 10 + 3 * 2 = 16
(a + b) * c = (10 + 3) * 2 = 26
a * b + c - 5 = 10 * 3 + 2 - 5 = 27
a ** b % c = 10 ** 3 % 2 = 0
π Method 2: Let Command
Syntax
let "variable = expression"
let variable=expression
Example 1: Basic Let Operations
#!/bin/bash
# Script: let_operations.sh
# Purpose: Demonstrate let command
a=10
b=3
echo "Using let command:"
echo ""
# Addition
let "sum = a + b"
echo "sum = ${sum}"
# Multiplication
let "product = a * b"
echo "product = ${product}"
# Division
let "quotient = a / b"
echo "quotient = ${quotient}"
# Modulo
let "remainder = a % b"
echo "remainder = ${remainder}"
Output:
Using let command:
sum = 13
product = 30
quotient = 3
remainder = 1
Example 2: Let with Increment
#!/bin/bash
# Script: let_increment.sh
# Purpose: Demonstrate let with increment
counter=0
echo "Initial counter: ${counter}"
let "counter++"
echo "After let counter++: ${counter}"
let "counter += 5"
echo "After let counter += 5: ${counter}"
let "counter *= 2"
echo "After let counter *= 2: ${counter}"
Output:
Initial counter: 0
After let counter++: 1
After let counter += 5: 6
After let counter *= 2: 12
π§ Method 3: Expr Command
Syntax
result=`expr $a + $b`
result=$(expr $a + $b)
Important Notes
- Spaces are required around operators
- Multiplication requires escaping:
\* - Slower than double parenthesis (external command)
Example 1: Basic Expr Operations
#!/bin/bash
# Script: expr_operations.sh
# Purpose: Demonstrate expr command
a=10
b=3
echo "Using expr command:"
echo ""
# Addition (spaces required)
sum=$(expr $a + $b)
echo "sum = ${sum}"
# Subtraction
diff=$(expr $a - $b)
echo "diff = ${diff}"
# Multiplication (escape the *)
product=$(expr $a \* $b)
echo "product = ${product}"
# Division
quotient=$(expr $a / $b)
echo "quotient = ${quotient}"
# Modulo
remainder=$(expr $a % $b)
echo "remainder = ${remainder}"
Output:
Using expr command:
sum = 13
diff = 7
product = 30
quotient = 3
remainder = 1
Example 2: Expr with Backticks (Legacy)
#!/bin/bash
# Script: expr_backticks.sh
# Purpose: Demonstrate expr with backticks
a=10
b=3
# Using backticks (legacy syntax)
sum=`expr $a + $b`
product=`expr $a \* $b`
echo "sum = ${sum}"
echo "product = ${product}"
Output:
sum = 13
product = 30
π Complete Arithmetic Examples
Example 1: Calculator Script
#!/bin/bash
# Script: calculator.sh
# Purpose: Simple calculator using arithmetic operations
read -p "Enter first number: " num1
read -p "Enter operator (+, -, *, /): " operator
read -p "Enter second number: " num2
case $operator in
+)
result=$((num1 + num2))
;;
-)
result=$((num1 - num2))
;;
\*)
result=$((num1 * num2))
;;
/)
if [ $num2 -eq 0 ]; then
echo "Error: Division by zero"
exit 1
fi
result=$((num1 / num2))
;;
*)
echo "Error: Invalid operator"
exit 1
;;
esac
echo "${num1} ${operator} ${num2} = ${result}"
Output:
Enter first number: 10
Enter operator (+, -, *, /): +
Enter second number: 5
10 + 5 = 15
Example 2: Loop with Arithmetic
#!/bin/bash
# Script: loop_arithmetic.sh
# Purpose: Use arithmetic in loops
echo "=== Counting from 1 to 10 ==="
for ((i = 1; i <= 10; i++)); do
echo -n "${i} "
done
echo ""
echo ""
echo "=== Counting by 2s from 0 to 20 ==="
for ((i = 0; i <= 20; i += 2)); do
echo -n "${i} "
done
echo ""
echo ""
echo "=== Countdown from 5 to 1 ==="
for ((i = 5; i >= 1; i--)); do
echo -n "${i} "
done
echo ""
Output:
=== Counting from 1 to 10 ===
1 2 3 4 5 6 7 8 9 10
=== Counting by 2s from 0 to 20 ===
0 2 4 6 8 10 12 14 16 18 20
=== Countdown from 5 to 1 ===
5 4 3 2 1
Example 3: Statistics Calculator
#!/bin/bash
# Script: statistics.sh
# Purpose: Calculate statistics using arithmetic
numbers=(10 20 30 40 50)
sum=0
count=0
echo "Numbers: ${numbers[@]}"
echo ""
# Calculate sum
for num in "${numbers[@]}"; do
sum=$((sum + num))
count=$((count + 1))
done
# Calculate average
average=$((sum / count))
echo "Sum: ${sum}"
echo "Count: ${count}"
echo "Average: ${average}"
Output:
Numbers: 10 20 30 40 50
Sum: 150
Count: 5
Average: 30
Example 4: Factorial Calculation
#!/bin/bash
# Script: factorial.sh
# Purpose: Calculate factorial using arithmetic
read -p "Enter a number: " n
if [ $n -lt 0 ]; then
echo "Error: Factorial not defined for negative numbers"
exit 1
fi
factorial=1
for ((i = 1; i <= n; i++)); do
factorial=$((factorial * i))
done
echo "Factorial of ${n} = ${factorial}"
Output:
Enter a number: 5
Factorial of 5 = 120
Example 5: Arithmetic Comparison
#!/bin/bash
# Script: arithmetic_comparison.sh
# Purpose: Use arithmetic in comparisons
a=10
b=5
echo "a = ${a}, b = ${b}"
echo ""
if [ $((a + b)) -gt 10 ]; then
echo "a + b is greater than 10"
fi
if [ $((a * b)) -eq 50 ]; then
echo "a * b equals 50"
fi
if [ $((a - b)) -lt 10 ]; then
echo "a - b is less than 10"
fi
if [ $((a % b)) -eq 0 ]; then
echo "a is divisible by b"
fi
Output:
a = 10, b = 5
a + b is greater than 10
a * b equals 50
a - b is less than 10
a is divisible by b
π― Practical Use Cases
1. Loop Counters
for ((i = 1; i <= 10; i++)); do
echo "Iteration $i"
done
2. Calculations
total=$((price * quantity))
discount=$((total * 10 / 100))
3. Comparisons
if [ $((a + b)) -gt 100 ]; then
echo "Sum is greater than 100"
fi
4. Incrementing Values
counter=$((counter + 1))
((counter++))
5. Modulo Operations
if [ $((number % 2)) -eq 0 ]; then
echo "Even number"
fi
β Best Practices
- Always use
$((expression))syntax (modern and recommended) - Avoid
exprcommand (slower, external command) - Use
letonly for legacy compatibility - Quote variables in expressions:
$((${var} + 5)) - Check for division by zero before dividing
- Use meaningful variable names
- Document complex calculations
- Test arithmetic with various inputs
- Remember: Bash does integer arithmetic only
- Use
bcorawkfor floating-point calculations
π Navigation
β¬ οΈ Previous: Default Values
π Current Location: Arithmetic Operations (You are here)
β‘οΈ Next Step: Module 4: Conditional Statements
πΊοΈ Full Path: Module 3: Variables & Input β Reading User Input β Command-Line Arguments β Command Output β Read-Only Variables β String Conversion β Substring Operations β Default Values β Arithmetic Operations
π Additional Resources
- π Bash Manual - Arithmetic Expansion: gnu.org/software/bash/manual/html_node/Arithmetic-Expansion.html
- π Shell Scripting Guide: tldp.org/LDP/abs/html/arith.html
- π‘ Advanced Bash Scripting: tldp.org/LDP/abs/html/
π Excellent! Arithmetic Operations Complete! π