Remove trailing space

Hi

I am trying to remove trailing space from a string.

value=${value%% }

It is not working. What might be the issue with the above snippet.

try:

value=$(echo $value)

Only trailing space, try:

value=${value%"${value##*[! ]}"}

--
The issue with value=${value%% } is that there is no wildcard, so it is equivalent to value=${value% } , i.e. remove one trailing space.

Try with a backslash:

value=${value%%\ }

It only works in ksh,bash,zsh, and Posix sh. Not in Unix standard shell.

The backslash won't matter. ${value%% } , ${value%%\ } , ${value% } , and ${value%\ } all expand to the value of the variable value with a single trailing space removed (if there was one) when using any shell that performs shell variable expansions as specified by the POSIX standards and the Single UNIX Specifications. (The Bourne shell and shells derived from csh do not recognize this syntax.)

Hi,

Thanks for the quick reply.

When I try to put it in "eval" command it is not accepting.
Is there any way to use/avoid trailing space here.

eval $value=\"${arr["$value"]}\"

present output is "tmp= lib" (please observe there is a space after =)

expected output is "tmp=lib" (without trailing space)

What trailing space? I don't see what this has to do with your original question. If this is a new problem, then please open a new thread for this.

If I don't understand anything then I do it longhand...

This DEMO strips spaces from anywhere in any type of ASCII string...

One could make it much simpler and into a function and call it.

In this case it removes spaces but could be ANY ASCII character...

BTW it took me longer to type it up than work it out...

#!/bin/sh
# Just a DEMO longhand example of doing it for yourself...
# Genius status not required...
# Note the space character on line 15 could be ANY ASCII character...
count=0
remove_space=""
new_value=""
value="   tmp= lib   _with_  spaces  _  anywhere...       "
str_len=`printf ${#value}`
# Ensure str_len is _subscript_ compatible...
str_len=$[ ( $str_len - 1 ) ]
for count in $( seq 0 $str_len )
do
	remove_space=`printf "${value:$count:1}"`
	if [ "$remove_space" == " " ]
	then
		remove_space=""
	fi
	new_value=$new_value$remove_space
done
value=$new_value
printf "$value"
# Prints "tmp=lib_with_spaces_anywhere..." to the terminal without a newline...