Bash Arrays, Strings, and Text Handling

Indexed and associative arrays, string handling, read/mapfile, and common Bash text-processing patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Indexed Arrays
Create indexed array
files=(a.txt b.txt c.txt)

# Create an indexed array.

Access array element
echo "${files[1]}"

# Read an array element by index.

Expand all array items
printf '%s
' "${files[@]}"

# Expand all array items safely.

Array length
echo "${#files[@]}"

# Count array elements.

Append array element
files+=(d.txt)

# Append one or more elements to an array.

Loop through array
for f in "${files[@]}"; do echo "$f"; done

# Iterate through array elements safely.

Unset array element
unset 'files[1]'

# Remove one indexed element.

## Associative Arrays
Create associative array
declare -A ports=([http]=80 [https]=443)

# Declare an associative array.

Read associative array item
echo "${ports[https]}"

# Read a value by key.

List associative array keys
printf '%s
' "${!ports[@]}"

# Expand associative array keys.

Loop through key/value pairs
for k in "${!ports[@]}"; do echo "$k=${ports[$k]}"; done

# Iterate through an associative array.

## String Operations
Lowercase string
name='Hello World'
echo "${name,,}"

# Convert a string to lowercase.

Uppercase string
name='Hello World'
echo "${name^^}"

# Convert a string to uppercase.

Trim prefix pattern
url='https://example.com'
echo "${url#https://}"

# Strip a matching prefix from a string.

Trim suffix pattern
file='archive.tar.gz'
echo "${file%.gz}"

# Strip a matching suffix from a string.

Split string into array
IFS=, read -r -a parts <<< 'red,green,blue'
printf '%s
' "${parts[@]}"

# Split a delimited string into an array.

Join array with delimiter
(IFS=,; echo "${parts[*]}")

# Join array elements using IFS.

## Reading Input
Prompt user for input
read -r -p 'Enter name: ' name

# Read one line from stdin with a prompt.

Read secret silently
read -r -s -p 'Password: ' password; echo

# Read secret input without echoing characters.

Load file into array
mapfile -t lines < file.txt

# Read all lines of a file into an array.

Read delimited fields
IFS=: read -r user shell <<< 'root:/bin/bash'
echo "$user $shell"

# Parse delimited input into multiple variables.