How to clear the string with bash

Rustam Atai3 min
  • quick-tip

Sometimes you need an easy way to drop part of a string in a Bash script.
This is especially useful when working with logs or other string collections.


🧩 Parameter Expansion

${var#*SubStr}   # remove shortest match from start up to first occurrence of SubStr
${var##*SubStr}  # remove longest match from start up to last occurrence of SubStr
${var%SubStr*}   # remove shortest match from end starting at last occurrence of SubStr
${var%%SubStr*}  # remove longest match from end starting at first occurrence of SubStr

⚙️ How It Works

  • # → removes from the start (shortest match)
  • ## → removes from the start (longest match)
  • % → removes from the end (shortest match)
  • %% → removes from the end (longest match)

📌 Example

export ips=ip1,ip2,ip3

firstIP=${ips%%,*}
echo $firstIP

Output:

ip1
How to clear the string with bash - Cloud Blog and Tools