The first command, in its entirety, is the command we’re interested in copying. In the second command, the !! history expansion event designator selects the previously executed command, and the q modifier wraps the command in quotation marks, escaping characters as necessary. Wrapping the command in quotation marks turns it into a single argument to the second echo, which pipes it into xsel’s standard input. Although it is not obvious from any of the output in the example, the clipboard ends up containing echo 'foo bar' exactly.
You might have xclip(1) instead of xsel(1), in which case you’ll need to pass different options, and on macOS you will probably want to use pbcopy(1).