Shell trick to pipe multiple "inputs" to a program
I’m currently testing a little assembly language program. The details aren’t important, but part of the test is to provide input to STDIN.
Rather than have to actually type something on the keyboard every single
time I test, I’ve been piping a string with echo in a script like so:
echo 'hello' | ./test-program
Output:
Testing... Got 'hello'.
But today, I added a second part that needs another sequence of input from STDIN.
Testing... Got 'hello'. Again... Got ''.
Since the piped input was done after "hello", the second attempt to read from STDIN gets nothing.
I can’t just send a second line of text. The first read of STDIN will happily gobble up newlines or just about anything else I throw at it…
It’s looking for a NUL (0) to indicate the end of input.
And that’s when it hit me: Can I send a literal 0 to end the first
input and start the second one?
Yeah, it worked! I used the printf command like so:
printf 'hello\0world' | ./test-program
And now my second attempt to read STDIN gets the second half of the piped input:
Testing... Got 'hello'. Again... Got 'world'.
I don’t know if that works for every program? I can’t think of any standard Unix utilities that take several inputs from STDIN. It would be interesting to test this on them.