Bash Snippet: Trim Function

Occasionally I find myself wanting to removing leading and/or trailing occurrences of a character or string from a larger string in bash. A couple common uses are removing quotes, or stripping an unknown number of spaces leading into the data of interest. This can be done pretty easily with other methods such as awk or sed, but with the disadvantage of requiring external commands. This a pure bash implementation using only shell built-ins. It might be better to rewrite this with $BASH_REMATCH, but this is what I currently have.

code.bash
#!/bin/bash

trim () {
	str="$1"
	match="$2"
	# trim spaces by default
	if [ -z "$match" ]; then
		match=" "
	fi
	# trim leading
	while [ "${str:0:${#match}}" == "$match" ];
	do
		str="${str:${#match}:${#str}}"
	done
	# trim tailing
	while [ "${str:$((${#str}-${#match}))}" == "$match" ];
	do
		str="${str:0:$((${#str} - ${#match}))}"	
	done
	echo "$str"
}

#Remove leading and trailing spaces
example="    Hello     "
echo "`trim  "$example" " "`"

#The second parameter is optional when removing spaces
example="    Hello     "
echo "`trim  "$example"`"


#Remove leading and trailing occurences of "word"
example="wordHelloword"
echo "`trim  "$example" "word"`"

One comment on “Bash Snippet: Trim Function