I have a shell script with this code:
var=`hg st -R "$path"`
if [ -n "$var" ]; then
echo $var
fi
But the conditional code always executes, because hg st
always prints at least one newline character.
$var
(like trim()
in PHP)?or
I could use sed or AWK, but I'd like to think there is a more elegant solution to this problem.
A simple answer is:
echo " lol " | xargs
Xargs will do the trimming for you. It's one command/program, no parameters, returns the trimmed string, easy as that!
Note: this doesn't remove all internal spaces so "foo bar"
stays the same; it does NOT become "foobar"
. However, multiple spaces will be condensed to single spaces, so "foo bar"
will become "foo bar"
. In addition it doesn't remove end of lines characters.