how to exit ssh terminal code example

Example 1: exit ssh

CTRL + d causes a logout. logout causes an exit. exit on its own is different only because it allows you to specify a non-zero exit code in case it's needed. So the first 3 options are equivalent.

Killing ssh, or the terminal will just break the connection. I'm not sure what you're going for with "gentle", but that is not it.

Assuming that by gentle you meant closing connections without errors on either side, just keep using CTRL + d

Example 2: exit ssh session in shell script

1. closing the shell session, e.g. with exit followed by Enter, or Ctrl-d usually allows you to exit the ssh session normally,
OR
2. in the case where you have a bad connection and the shell is unresponsive, hit the Enter key, then type ~. and ssh should immediately close and return you to your command prompt.