0

So I have searched for this but I didn't find anything which addresses this. I frequently connect to a remote server through ssh on which I don't have sudo permissions.

Let's say the connection gets terminated/reset by the remote server by inactivity or other reasons. Now all I want is that before the remote server terminates my connection it should run a pwd. I know there are ways to prolong/prevent remote server from terminating your connection, but I would like it to run a custom command of my choice before termination

0

In Bash, you could set up a trap for EXIT to have the shell run a command when it exits:

trap 'do something here' EXIT

That works for shells exiting due to end of input (^D), timeout through TMOUT, being shot with a SIGTERM or SIGHUP, and remote shells over SSH where the SSH client dies.

However, when running over SSH (or another network connection), the shell can't react to the connection closing before it's really closed, so anything it prints won't get to the other end at that point. You could run a command that modifies things on the remote end, but something like pwd, which just prints stuff, won't do anything useful.

If you do want the last working directory shown, you could have the shell print it on the prompt, with the \w escape.

  • Yes I was also thinking on similar lines that the shell cant catch imminent termination of connection. Thanks! – Shachit Iyer May 21 '18 at 21:23
  • @ShachitIyer, yeah, especially a "reset by the remote server by inactivity" you mentioned sounds like something that probably would start by breaking the network connection, and then leaving the shell to clean up after itself when it sees the connection has gone away. – ilkkachu May 21 '18 at 21:31
0

Similarly to ilkkachu's answer, you may create ~/.bash_logout with a set of commands to run when the bash login shell exits. And similarly to the issue in his answer, this would not be run if the SSH connection was terminated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.