Shell script variable comparison
In my day job, i came across a task to write a shell script for Almquist shell (also known as ash shell) to do string comparison.
At first, i use Linux bash shell to create the script.
if [[ $CHANGE =~ spif ]]; then echo “match”; fi
The comparison works in bash shell. However, in ash shell, there is an error, sh: =~ unknown operand.
After some research, i found a method which works in both bash and ash shell.
if [ -z "{$CHANGE##*spif*}" ]; then echo “match”; fi
This will print “match” in bash or ash shell. The ## is probably from Korn shell’s pattern matching operator.
Furthermore, to match and modify a string with regular expression, such as we want to match a string starting with spif and replace it with a new string:
“s/spif.*/newstring/g”
The .* will match till end of the string. If we want to only match to the next space, use:
“s/spif[^ \t]*/newstring/g”
To test: we set an env variable to:
ourargs=”hello world”newvar=$(echo $ourargs | sed -e “s/hello[^ \t]*/distant/g”)
We can see that, indeed, newvar is set to distant world.