How do I pass a password to hdiutil attach?
Ah! A little more digging, and careful reading of the man page. I need a null terminated string.

So 

printf '%s\0' 'test' | hdiutil attach test.sparsebundle -stdinpass


works.