0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Trim Whitespace in Bash: Simple Methods Explained

In Bash, you can trim whitespace using parameter expansion like var="${var##+([[:space:]])}" for leading and var="${var%%+([[:space:]])}" for trailing spaces. Another simple way is to use sed or awk commands to remove spaces from strings.
📐

Syntax

Here are common ways to trim whitespace in Bash:

  • Parameter expansion: Removes spaces using shell patterns.
  • sed command: Uses stream editor to delete spaces.
  • awk command: Processes text to trim spaces.
bash
var="  example  "
# Remove leading whitespace
shopt -s extglob
var="${var##+([[:space:]])}"
# Remove trailing whitespace
var="${var%%+([[:space:]])}"
💻

Example

This example shows how to trim leading and trailing spaces from a variable using Bash parameter expansion with extended globbing enabled.

bash
#!/bin/bash
shopt -s extglob
input="   Hello, Bash!   "
trimmed="${input##+([[:space:]])}"
trimmed="${trimmed%%+([[:space:]])}"
echo "Original: '$input'"
echo "Trimmed: '$trimmed'"
Output
Original: ' Hello, Bash! ' Trimmed: 'Hello, Bash!'
⚠️

Common Pitfalls

Common mistakes include not enabling extglob before using advanced pattern matching, which causes parameter expansion to fail. Also, using simple var=\"$var\" does not trim spaces. Another pitfall is assuming echo trims spaces, but it does not.

bash
# Wrong way (no extglob enabled)
input="  text  "
trimmed="${input##+([[:space:]])}"
echo "'$trimmed'"  # Outputs original with spaces

# Right way
shopt -s extglob
trimmed="${input##+([[:space:]])}"
trimmed="${trimmed%%+([[:space:]])}"
echo "'$trimmed'"  # Outputs trimmed text
Output
' text ' 'text'
📊

Quick Reference

MethodDescriptionExample
Parameter ExpansionTrim spaces using shell patternsshopt -s extglob; var="${var##+([[:space:]])}"; var="${var%%+([[:space:]])}"
sedRemove spaces with stream editorecho "$var" | sed 's/^ *//;s/ *$//'
awkTrim spaces using awkecho "$var" | awk '{$1=$1;print}'

Key Takeaways

Enable extglob with shopt -s extglob before using advanced parameter expansion.
Use parameter expansion to trim leading and trailing whitespace efficiently.
sed and awk are useful alternatives for trimming spaces in Bash scripts.
Simple variable assignment or echo does not remove whitespace.
Test your trimming commands to avoid unexpected results.