Prevent race condition and use a here document