How to impose memory limits on a shell script?

You can limit the memory usage by a Bash Script, doing the follow.

Limit the memory usage by kb (2GB in this example):

ulimit -m 2048000

Limit virtual memory usage:

ulimit -v 2048000

Set virtual memory limit to be hard limit, so that process will be killed when exceeding this limit:

ulimit -H -v

I think this can do what you want.