Use screen to run long-running commands, such as port-forwarding ssh sessions, on your local or remote machines.

As opposed to nohup shenanigans, the advantage here is that this is just like a terminal session, but out of sight. The session is addressable, recallable by name.

Scenario: You make a remote port available locally. You run a bunch of operations on the service now available at your local port. You terminate the port-forwarding.

#!/bin/bash -e

screen -S "${SCREEN_NAME}" -dm ssh -L 8002:localhost:8002 ec2-user@<server-addr>

# to run multiple commands:
# screen -S "${SCREEN_NAME}" -dm bash -c 'ssh -L 8002:localhost:8002 ec2-user@<server-addr>; echo "connected"'

screen -ls
#!/bin/bash -e

screen -S "${SCREEN_NAME}" -X quit

After running ./, the remote service running on port 8002 becomes available locally. If for any reason the ssh command fails, the screen terminates.

You can always inspect the status of your session with screen -r ${SCREEN_NAME}.