I'm putting together some unit tests for a dash
shell script I've inherited and, given the large number of tests we want to add, I want to keep them as concise as possible.
To do this, I've added a check
helper function to handle pass or failure of a test. It basically receives the return code $?
from the previous command and passes or fails the test based on that. This allows me to simply implement a one-liner test (of which there are many) as:
for td in 1.1.1.999 {{lots of other invalid IPs}} ; do
isInvalidIpV4 ${td} ; check is-true $? "Checking ${td} is invalid"
done
for seg in 0 1 9 10 99 100 254 255 ; do
td="${seg}.${seg}.${seg}.${seg}"
isInvalidIpV4 ${td} ; check is-false $? "Checking ${td} is valid"
done
Now this is reasonably good since it gets each test down to a single line but, in my OCD quest for perfection, I wonder if there's even more scope for reduction.
I know that, like bash
, there is the capability to run a command and use its output in another command, along the lines of:
echo "Lowercase name is $(echo PaxDiablo | tr '[A-Z]' '[a-z]')"
but I was wondering if there were a way to do this same substitution with the return code of a command.
That would mean my test line would be able to have that annoyingly repeated $?
removed, changing from:
isInvalidIpV4 ${td} ; check pass $? "${td} should be invalid"
to something like:
check pass $[isInvalidIpV4 ${td}] "${td} should be invalid"
where $[]
is the mythical "use return code" substitution operator.
Does dash
have this facility or is there a more concise way to do it than what I've currently done?
Just keep in mind, other shells are not an option here, this is an embedded system for which dash
is the only shell provided.