Would it be useful or realistic to attach a knife to a gun? Would it be in anyway helpful in a fight in a smaller space or would it just get in the way and be unhelpful?
Well, that’s called a bayonet. They do exist. These date back to single shot firearms, where you’d be left without a functional weapon while reloading in an era when melee combat was still the norm. As with a lot of elements of military tradition and hardware, bayonets have massively outlived their usefulness.
Modern bayonets are (usually) functional combat knives with attachment points designed to lock onto a rifle. That said, some rifles do include integrated bayonets, which can be collapsed and stored on the gun.
Generally speaking, the only time you’d use a bayonet is when the rifle cannot be fired. Either because it’s out of ammunition, malfunctioning, or you’re in some incredibly specific situation where firing it would be a profoundly bad idea. Otherwise, even in close quarters, you’re better off pumping two or three rounds into someone.
Which leads back to the question about usefulness; not very. Detachable ones can be useful in the sense that you need a knife and just happen to be carrying one, but a well equipped combatant should have a knife or other cutting implement in easy reach regardless. In very rare circumstances, it’s a good augment for your rifle, but that’s more of an, “in theory,” consideration than a practical application.
Sticking a bayonet on a pistol (or revolver) isn’t a great idea. You’ll see these occasionally as novelty items, but you’d be better off simply bringing a separate knife. The one advantage a bayonet has, when it’s mounted on a rifle, is reach. Slapping one on a pistol makes the blade harder to control, without increasing its range.