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 2NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | tr -d '[:space:]')" # NEW_VARIABLE='aaa bbb'This method uses the
trcommand to delete all whitespace characters, both leading and trailing, in the variableVARIABLE_NAME. -
Remove Only Leading White Spaces:
1 2NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/^[[:space:]]*//')" # NEW_VARIABLE='aaa bbb 'Here,
sedis used to remove only the leading whitespace characters from the variable. -
Remove Only Trailing White Spaces:
1 2NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/[[:space:]]*$//')" # NEW_VARIABLE=' aaa bbb'This approach utilizes
sedto eliminate trailing whitespace characters from the variable. -
Remove All White Spaces (Leading, Trailing, and Inside):
1 2NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" # NEW_VARIABLE='aaabbb'Here,
sedis used twice. The first expression removes leading whitespaces, and the second one removes trailing whitespaces, effectively removing all whitespaces, including those inside the variable.
These methods provide flexibility depending on your specific requirements for whitespace removal in Bash.