Overview: Strings in Terminal (Bash)

Strings in terminal scripting are sequences of characters enclosed either in quotes or handled as text variables. Mastering string manipulation is essential for tasks like filename handling, messaging, or data parsing.

Declaring Strings

  • Simple String Assignment: my_string="Hello World"
  • Using Single Quotes (Literal Strings): my_string='Hello $USER' (no variable substitution)
  • Using Double Quotes (Interpolated Strings): my_string="Hello $USER" (variables are expanded)

String Output and Printing

  • Print a String: echo "Hello, World"
  • Using printf: printf "%s\n" "$my_string"

String Length

  • Get length: ${#my_string}
  • Example: echo "Length: ${#my_string}"

Substring Extraction

  • Extract from position: ${my_string:position} (starts from position)
  • Extract a range: ${my_string:position:length} (starts at position, length length)
  • Example: echo "${my_string:0:5}" (outputs Hello)

Substring Replacement

  • Replace First Occurrence: ${my_string/find/replace}
  • Replace All Occurrences: ${my_string//find/replace}
  • Example: echo "${my_string/World/Terminal}"

Concatenating Strings

  • Simple Concatenation: full_string="$string1$string2"
  • With separator: full_string="$string1 - $string2"
  • Example: echo "$full_string"

String Comparison

  • Equality: [[ "$a" == "$b" ]]
  • Inequality: [[ "$a" != "$b" ]]
  • Empty String: [[ -z "$a" ]] (zero length)
  • Non-Empty String: [[ -n "$a" ]]
  • Example:
    
    if [[ "$a" == "$b" ]]; then
        echo "Strings are equal"
    fi
            

Splitting Strings

  • Using IFS (Internal Field Separator):
    
    string="apple,banana,cherry"
    IFS=',' read -ra fruits <<< "$string"
    echo "${fruits[0]}" # outputs apple
                

String Trimming

  • Trim Leading/Trailing Spaces (Basic):
    
    string="  Hello World  "
    trimmed=$(echo "$string" | xargs)
    echo "$trimmed"
                

Changing Case

  • To Lowercase: ${string,,}
  • To Uppercase: ${string^^}
  • Example:
    
    text="Hello"
    echo "${text,,}" # hello
    echo "${text^^}" # HELLO
                

Advanced String Operations

  • Remove prefix: ${string#pattern} (shortest match)
  • Remove longest matching prefix: ${string##pattern}
  • Remove suffix: ${string%pattern}
  • Remove longest matching suffix: ${string%%pattern}
  • Example:
    
    path="/home/user/file.txt"
    echo "${path##*/}"   # file.txt
    echo "${path%/*}"    # /home/user