Trim the Whitespace Characters From a Bash Variable
In Bash, you can trim whitespace characters from a variable using various methods, as shown in your code. Here’s a breakdown of the different approaches:
-
Remove Leading and Trailing White Spaces:
1 2
NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | tr -d '[:space:]')" # NEW_VARIABLE='aaa bbb'
This method uses the
tr
command to delete all whitespace characters, both leading and trailing, in the variableVARIABLE_NAME
. -
Remove Only Leading White Spaces:
1 2
NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/^[[:space:]]*//')" # NEW_VARIABLE='aaa bbb '
Here,
sed
is used to remove only the leading whitespace characters from the variable.