The study of the history of Shakespeare’s texts is a life-long discipline for English literature scholars (see Fredson Bowers’ definitive Principles of Bibliographical Description, 1949).
They begin with records of Shakespeare performances in his lifetime, and divide the texts (that is, the physical written copies of the lines and stage directions) into several kinds, called “fair” and “foul” copies. Fair copies, legitimate authorized editions of the complete play, printed during Shakespeare's lifetime, are most reliable as historical records, because they have not been tampered with nor edited, and were presumably overseen by the author; foul copies include actors’ “sides” (the actors were not given the entire script, just those scenes where their character appeared), copies written down by audience members (usually to be stolen for another acting company), or later printed copies often containing printing errors that obfuscate the line’s meaning (in the description of Falstaff’s death, “and tabled of green fields” for example, probably should have been “and babbled of green fields”). Finally, after Shakespeare’s death, his friends and colleagues gathered his plays into the Folio edition of 1623 (18 plays appear here exclusively). What saved Shakespeare’s plays in the next generations was their popularity on stage, even through the Restoration, and the 18th and 19th centuries.