Why not just put "sudo gainroot" at the top of the script before all the commands? No need to pipe it then...