[aklug] Re: bash assert function?

From: <bryanm@acsalaska.net>
Date: Wed May 23 2012 - 19:09:14 AKDT

On Wed, May 23, 2012 2:25 pm, Christopher Howard wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hey guys, my bash is a bit rusty, but I'm trying to use a bash script
> as a unit test in one of my software packages. I want to make a little
> "assert" function like so:
>
> code:
> - --------
> # Params:
> # 1) LINENO
> # ...) expression to test
> function assert
> {
> [ $# -gt 1 ] || die "assert requires at least two parameters"
> lineno=$1
> shift 1
> if ! [ $@ ] ; then
> echo "assert test failed at line $lineno, test expression $@"
> return 1
> else
> return 0
> fi
> }
> - --------
>
> The idea being to do asserts like:
>
> code:
> - --------
> results=`some_test_command -f foo`
> assert $LINENO "$results" = "string value" || die
> - --------
>
> However, this chokes if I try something like:
>
> code:
> - --------
> assert $LINENO "a b" = "a b"
> # test inside assert() chokes on having "too many arguments"
> - --------
>
> I suppose I could do the test outside of the assert function, and just
> pass in the results, but that would be kind of lame because then the
> assert function wouldn't be able to echo the test expression.
>
> Any helpful thoughts?

Like many bash problems, this is a quoting issue. When you pass
 "a b"
to the function, the quotes are removed, leaving
 a b

You can see this with echo:
$ echo "a b" = "a b"
a b = a b

And then, when you do the test:
$ [ a b = a b ]
-bash: [: too many arguments

You need to pass the arguments to the function in a way that will
leave any included spaces quoted (or escaped). In this particular
example, you could do this:
$ echo '"a b"' = '"a b"'
"a b" = "a b"

In fact, I think the single quotes may work as a fairly general
solution, but don't ... (ahem) ... quote me on that. Depending
on what you're actually passing to the function, you may have to
play around with the quoting syntax a bit.

--
Bryan Medsker
bryanm@acsalaska.net
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Wed May 23 19:09:20 2012

This archive was generated by hypermail 2.1.8 : Wed May 23 2012 - 19:09:20 AKDT