al-Khidr has roots in Jewish texts. All 3 of the stories in al-Kahf (sleepers in the cave, Moses and al-Khidr and Dhul Qarnayan) are references to stories found in Muhammad's environment. Islamic exegetes even acknowledge this as they say the verse was revealed in response to a challenge from some 'people of the book' (often given as Jews, but 2 of the stories are really Christian) who wanted to test Muhammad.
This servant of God is called al-K̲h̲aḍir by the majority of the commentators. Others, however, identify him with Mūsā’s servant (see below). Both interpretations have their roots in Oriental legends. The Ḳurʾānic story may be traced back to three main sources: the Gilgames̲h̲ epic, the Alexander romance and the Jewish legend of Elijah and Rabbi Joshua ben Levi. The two first are, of course, again closely related to one another; at the same time it should be noted that the fish episode is lacking in the epic and is only found in the romance...
The Jewish legend (printed in Jellinek, Bet ha-Midrasch , v, 133-5) tells how Rabbi Joshua ben Levi goes on a journey with Elijah under conditions laid down by Elijah, like those above of the servant of God in the Ḳurʾān. Like the latter, Elijah does a number of apparently outrageous things, which affects Joshua as it did Mūsā. Zunz,Gesammelte Vorträge , x, 130 first pointed out the similarity of this story to the Ḳurʾānic legend. A comparison of the main features of these three sources with Sūra XVIII, 59 ff. suggests the following conclusions, questions and hypotheses...
The commentators, ḥadīt̲h̲ , and historians have collected a mass of statements around the Ḳurʾānic story, additions which, like the story itself, came for the most part from the three sources already mentioned.
The first question discussed is whether the principal character is Mūsā b. ʿImrān or Mūsā b. Mis̲h̲ā (= Manasseh) b. Yūsuf b. Yaʿḳūb, i.e. a descendant of the patriarch Jacob (al-Rāzī, Mafātīḥ al-g̲h̲ayb , iv, 333; al-Zamak̲h̲s̲h̲arī. Kas̲h̲s̲h̲āf , on v. 59). Commentators are almost unanimous in favour of the former alternative and base their opinion on the following legend which is transmitted in several forms. When Mūsā, the famous prophet, was one day preaching to the children of Israel, he was asked if there was any man wiser than he. When he replied in the negative, Allāh revealed to him that his pious servant, al-K̲h̲aḍir, was wiser than he. He thereupon decided to visit this wise man. The story comes from Jewish legend; it is found in a considerable number of Arabic sources (al-Buk̲h̲ārī, ʿIlm , bāb 16, 19, 44; Anbiyāʾ ,bāb 27; Tafsīr , Sūra XVIII, bāb 2-4; Muslim, Faḍāʾil , tr. 170-4; al-Tirmid̲h̲ī, Tafsīr, Sūra XVIII, bāb 1; al-Ṭabari, i, 417; Tafsīr, xv, 165 f; Fak̲h̲r al-Dīn al-Rāzi, op. cit., iv, 333).(EI2)