Core Concepts in Bash Scripting
A shell script is a concise program designed to automate tasks on a computer. These scripts are plain text files, editable with any text editor, and executed by an interpreter without prior compilation.
Your Initial Script
Create a file named greeting.sh with the following content:
#!/usr/bin/env bash
echo "Greetings, Universe!"
The shebang (#!) specifies the interpreter. Grant execute permission and run it:
chmod u+x greeting.sh
./greeting.sh
Working with Variables
Defining Variables
Assign values using an equals sign without spaces.
username="dev_user"
Rules:
- No spaces around
=. - Name can contain letters (case-sensitive), numbers (not at start), and underscores.
- Avoid reserved keywords.
- Conventionally, uppercase denotes constants.
Accessing Variables
Prefix the variable name with a dollar sign.
username="dev_user"
echo "User: $username"
Command Substitution vs. Variable Expansion
$()executes a command and substitutes its output. Backticks ` ` do the same.${}ensures correct variable expansion, especially when adjacent to other text. Example:
current_date=$(date +%Y-%m-%d)
echo "Today is $current_date"
# Equivalent with backticks
timestamp=`date +%s`
echo "Timestamp: $timestamp"
Immutable Variables
Mark a variable as read-only with readonly.
config_path="/etc/app/config"
readonly config_path
Removing Variables
Use unset to delete a variable. This fails for read-only variables.
unset temp_var
Predefined Variables
Special variables provide runtime information.
$?: Exit status of the last command.$1,$2, ...: Positional parameters. For the tenth and beyond, use${10}.
Other useful built-in variables:
#!/usr/bin/env bash
read -p "Enter input: "
echo "Parent PID: $PPID"
echo "Current directory: $PWD"
echo "Line number: $LINENO"
echo "Random number: $RANDOM"
echo "Last input (non-option): $REPLY"
echo "Option arg: $OPTARG, Option index: $OPTIND"
echo "Script duration (seconds): $SECONDS"
Environment Variables
View all with env. They are typically uppercase.
env
Set a new variable for the current session:
export APP_MODE="production"
export PATH="$HOME/.local/bin:$PATH"
To make permanent, add to ~/.bashrc (user-specific) or /etc/profile (system-wide).
Data Types and Structures
Declare different types of variables:
app_name="Data Processor" # String
declare -i item_count=100 # Integer
data_set=(10 20 30 40 50) # Indexed array
declare -A metadata # Associative array
metadata["version"]="1.2"
metadata["author"]="admin"
String Manipulation
Strings can use single or double quotes. Double quotes allow variable expansion and escape sequences. Single quotes treat everything literal.
app_desc="Processes data efficiently."
len=${#app_desc}
sub_str=${app_desc:0:9}
char_pos=$(expr index "$app_desc" "aeiou") # Find first vowel
Advanced extraction using patterns:
url="https://example.com/docs/api-guide.html"
echo "Full URL: $url"
echo "After first slash: ${url#*/}" # Removes up to first '/'
echo "After last slash: ${url##*/}" # Removes up to last '/'
echo "Before last slash: ${url%/*}" # Keeps part before last '/'
echo "Before first slash: ${url%%/*}" # Keeps part before first '/'
Arrays
Access elements by index, starting from 0.
data_set=(10 20 30 40 50)
third_element=${data_set[2]}
all_elements=("${data_set[@]}")
element_count=${#data_set[@]}
length_of_third=${#data_set[2]}
Associative Arrays
Store key-value pairs. Declare with -A.
declare -A server_info
server_info=(["ip"]="192.168.1.10" ["role"]="web")
# Or assign individually
server_info["status"]="active"
echo "IP Address: ${server_info[\"ip\"]}"