How to build all projects in a monorepo by starting a build in Jenkins?
Build tools like maven or gradle could benefit you greatly here. It would do exactly what you have in mind as long as you have child project definition (with a build.gradle in gradle or pom.xml in maven).

I would not recommend the script as it would mean you have to maintain and tweak it in the future. Instead, investing in build tools can give you great ROI as they do much more than just build.

At the end if you cannot integrate a build tool, go for the script. It is a good idea also.