5月30日 00:10

How to define and use arrays in Shell scripts? What are the common array operations?

Array operations in Shell scripts include array definition, access, iteration, and common operations.

Array Definition

Regular Arrays

bash
# Define empty array arr=() # Define array (space separated) arr=(apple banana cherry) # Define individually arr[0]="apple" arr[1]="banana" arr[2]="cherry" # Define using command output arr=($(ls *.txt))

Associative Arrays (Bash 4.0+)

bash
# Declare associative array declare -A arr # Define associative array arr[name]="John" arr[age]=25 arr[city]="Beijing" # Define all at once declare -A arr=([name]="John" [age]=25 [city]="Beijing")

Array Access

Access Single Element

bash
arr=(apple banana cherry) # Access element at specific index echo ${arr[0]} # Output: apple echo ${arr[1]} # Output: banana echo ${arr[2]} # Output: cherry # Access last element echo ${arr[-1]} # Output: cherry # Access non-existent index echo ${arr[10]} # Output: (empty)

Access All Elements

bash
# Access all elements echo ${arr[@]} # Output: apple banana cherry echo ${arr[*]} # Output: apple banana cherry # Access all element indices echo ${!arr[@]} # Output: 0 1 2 # Access array length echo ${#arr[@]} # Output: 3 echo ${#arr[*]} # Output: 3

Access Partial Elements

bash
# Access all elements starting from index 1 echo ${arr[@]:1} # Output: banana cherry # Access 2 elements starting from index 1 echo ${arr[@]:1:2} # Output: banana cherry # Access starting from 2nd to last element echo ${arr[@]: -2} # Output: banana cherry

Array Iteration

Iterate All Elements

bash
arr=(apple banana cherry) # Method 1: Use for loop for item in "${arr[@]}"; do echo "Item: $item" done # Method 2: Use index iteration for i in "${!arr[@]}"; do echo "Index $i: ${arr[$i]}" done # Method 3: Use C-style loop for ((i=0; i<${#arr[@]}; i++)); do echo "Index $i: ${arr[$i]}" done

Iterate Associative Array

bash
declare -A arr=([name]="John" [age]=25 [city]="Beijing") # Iterate keys for key in "${!arr[@]}"; do echo "Key: $key" done # Iterate key-value pairs for key in "${!arr[@]}"; do echo "$key: ${arr[$key]}" done

Array Operations

Add Elements

bash
arr=(apple banana) # Add to end arr+=(cherry) arr+=("date" "fig") # Add to specific position arr[2]="cherry" # Replace or add # Add using index arr[${#arr[@]}]="grape" # Add to end

Delete Elements

bash
arr=(apple banana cherry date fig) # Delete element at specific index unset arr[2] # Delete element at index 2 # Delete entire array unset arr # Delete associative array element declare -A arr=([name]="John" [age]=25) unset arr[name]

Modify Elements

bash
arr=(apple banana cherry) # Modify element at specific index arr[0]="orange" arr[1]="pear" # Batch modify for i in "${!arr[@]}"; do arr[$i]="${arr[$i]}_modified" done

Array Slicing

bash
arr=(one two three four five) # Slicing echo ${arr[@]:1:3} # Output: two three four # Slice and assign new_arr=(${arr[@]:1:3})

Array Sorting

Simple Sorting

bash
arr=(banana apple cherry date) # Lexicographic sort sorted=($(echo "${arr[@]}" | tr ' ' '\n' | sort)) echo "${sorted[@]}" # Numeric sort nums=(5 2 8 1 9) sorted_nums=($(echo "${nums[@]}" | tr ' ' '\n' | sort -n)) echo "${sorted_nums[@]}" # Reverse sort sorted_rev=($(echo "${arr[@]}" | tr ' ' '\n' | sort -r)) echo "${sorted_rev[@]}"

Deduplication

bash
arr=(apple banana apple cherry banana) # Remove duplicates unique=($(echo "${arr[@]}" | tr ' ' '\n' | sort -u)) echo "${unique[@]}"

Find Element

bash
arr=(apple banana cherry) # Check if element exists if [[ " ${arr[@]} " =~ " banana " ]]; then echo "Found banana" fi # Use function to find contains_element() { local e match="$1" shift for e; do [[ "$e" == "$match" ]] && return 0; done return 1 } if contains_element "banana" "${arr[@]}"; then echo "Found banana" fi

Find Index

bash
arr=(apple banana cherry) # Find element index get_index() { local element=$1 shift local arr=("$@") for i in "${!arr[@]}"; do if [[ "${arr[$i]}" == "$element" ]]; then echo $i return 0 fi done return 1 } index=$(get_index "banana" "${arr[@]}") echo "Index of banana: $index"

Practical Application Examples

File Processing

bash
# Get all .txt files files=($(ls *.txt)) # Iterate and process for file in "${files[@]}"; do echo "Processing: $file" # Process file done # Check if files exist if [ ${#files[@]} -eq 0 ]; then echo "No .txt files found" fi

Parameter Processing

bash
# Store parameters in array args=("$@") # Iterate parameters for arg in "${args[@]}"; do echo "Argument: $arg" done # Check for specific parameter if [[ " ${args[@]} " =~ " --verbose " ]]; then verbose=true fi

Data Statistics

bash
# Read data into array readarray -t lines < data.txt # Count lines echo "Total lines: ${#lines[@]}" # Count lines containing specific content count=0 for line in "${lines[@]}"; do if [[ "$line" =~ "pattern" ]]; then ((count++)) fi done echo "Matching lines: $count"

Configuration Management

bash
# Parse config file to associative array declare -A config while IFS='=' read -r key value; do config[$key]="$value" done < config.txt # Access configuration echo "Database: ${config[db_host]}" echo "Port: ${config[db_port]}"

Array Best Practices

  1. Always use quotes: "${arr[@]}" prevents issues with spaces and special characters
  2. Use ${#arr[@]} for length: Instead of ${#arr}
  3. Use ${!arr[@]} for indices: Safer when iterating
  4. Declare associative arrays: Use declare -A for associative arrays
  5. Avoid uninitialized indices: Check if index exists
  6. Encapsulate complex operations in functions: Improve code readability
  7. Note array indices start at 0: Consistent with other programming languages
标签:Shell