O'Bannon entered the Marine Corps on January 18, 1801. As a first lieutenant assigned to , he commanded a detachment of seven Marines and two Navy midshipmen in diplomatic Consul General William Eaton's (1764–1811) small army during the Tripoli campaign of the First Barbary War (1801–1805). In the combined operations with the U.S. Navy, he led the successful attack at the Battle of Derna, a coastal town in eastern modern Libya on April 27, 1805, giving the Marines' Hymn its line "to the shores of Tripoli." Lieutenant O'Bannon became the first man to raise a United States flag over foreign soil in time of war; O'Bannon's superior, William Eaton (1764–1811), a former Army officer, had raised the American flag several months earlier while traveling on the Nile River from Alexandria to Cairo, but it had not been in a time of war. According to Marine Corps legend, Hamet Karamanli was so impressed with O'Bannon's bravery that he gave him a Mameluke sword as a gesture of respect.