Morocco ended their 2019 Africa Cup of Nations (Afcon) Group D campaign with a 1-0 victory over South Africa in Egypt on Monday evening.
Bafana Bafana needed a victory in order to confirm their place in the Round of 16. They secured a narrow 1-0 victory over their Southern African rivals Namibia on Friday night, which kept them in contention to progress via third place.
Stuart Baxter made three changes to the team that faced the Brave Warriors with Holland-based midfielder Thulani Serero making his first appearance in the tournament.
The Atlas Lions had already secured their spot in the knockout phase after recording their second successive win when they edged out Ivory Coast 1-0 on Friday evening.
Baxter's counterpart, Herve Renard also made three changes with goalkeeper Mohamedi Munir replacing Yassine Bounou, who had kept clean sheets against Namibia and Ivory Coast.
The Atlas Lions knew that avoiding a defeat against Bafana would see them finish as group winners, but the North Africans pushed for an early goal as they made their intentions clear.
However, the South Africa defence was marshalled by their captain Thulani Hlatshwayo and looked solid in the early exchanges.
The two former Afcon champions upped the tempo after the half-hour mark as Percy Tau shot from range and his effort went inches wide of Munir's goal.
At the other end, Youssef En-Nesyri, who had netted against Ivory Coast on Friday, saw his low shot saved by a well-positioned Ronwen Williams in South Africa's goal.
South Africa and Morocco were locked at 0-0 at the interval following a first half which had few chances.
The two teams continued to struggle to create goalscoring opportunities after the restart and Renard decided to introduce France-based midfielder Youssef Ait Bennasser.
The 1976 Afcon champions were unlucky not to break the deadlock through Borussia Dortmund defender Achraf Hakimi, who is on loan from Spanish football heavyweights Real Madrid.
The full-back cut inside from the left-hand side before pulling the trigger and his powerful long-range shot beat Willams, but the crossbar came to Bafana's rescue.
The momentum was with two-time Afcon title-winning coach Renard's men in the latter stages of the game and they came close to scoring late through En-Nesyri.
Nordin Amrabat whipped in a good cross for the lanky forward, whose header went straight to Williams, who made a decent save as the 1996 Afcon winners survived a scare.
However, Williams was finally beaten in the 90th minute when Mbark Boussoufa scored from inside the box after South Africa had failed to clear the ball away and Morocco held on to win 1-0 on the night.
Bafana finished third in Group D and they could still advance to the knockout phase if results in other groups go their way.