PL/pgSQL function + client-side lo_import
psql is the wrong tool for this kind of job because it basically can't get results into variables. It's good for user interface and static scripts, but for
interactive scripting where results from one operation are to be piped into another, it falls short. The best solution is to switch to a real scripting language such as Perl or Python that have good client-side APIs, including large-objects streaming.

When limited to bash, it's still possible to operate psql from the outside with coproc to get results out and back in, but it's much more complicated.