[Code Example] Trim start & end white spaces in string bash

Total
0
Shares

In this article we will provide you code to trim white spaces in string from start & end using bash commands. You can use this code to sanitize strings received from user inputs and terminal commands.

Code Example –

trim() {
    : "${1#"${1%%[![:space:]]*}"}"
    : "${_%"${_##*[![:space:]]}"}"
    echo "$_"
}

sanitized_string=$(trim "   Just because animals cannot fight back, does not make them humans food.      ")

echo $sanitized_string

# Output: Just because animals cannot fight back, does not make them humans food.

Inspired From – Dylan Araps

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like