0

For work I ssh into various servers and will do various analysis jobs from within tmux sessions. When I want to end the ssh connection, I have a bad habit of running exit immediately, when what I should to is C-b d to detach from the session and then run exit to close the connection. Running exit in tmux kills the session so I'd like check if I'm in a tmux session before running exit.

I know I can use a simple -n $TMUX check to see if I'm in a tmux session and I've tried adding the following in my .bashrc:

alias exit='if -n $TMUX then echo "You are in a tmux session" else exit fi'

This doesn't work, I just get a hanging > prompt and I'm not sure why. I'm pretty sure part of it is that I'm running the exit command within the alias definition, so that's probably not a great circular logic there.

Any thoughts on how to accomplish this would be appreciated.

2 Answers2

2

Correct syntax is:

alias exit='if [ ! -z "$TMUX" ]; then echo "You are in a tmux session"; else exit; fi'
svlasov
  • 9,923
  • 2
  • 38
  • 39
2

Extending @svlasov's answer: it's most often recommended[*] to use functions instead of aliases -- they can be made more readable and are more flexible particularly regarding argument handling.

exit() {
    if [[ -n $TMUX ]]; then
        echo "You are in a tmux session"
    else
        builtin exit "$@"
    fi
}

builtin is required to prevent the function from invoking itself (aliases don't do this).

[*] even by the bash manual

For almost every purpose, shell functions are preferred over aliases.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • This works perfectly, thank you! – caligapiscis Jun 30 '23 at 13:12
  • 1
    Be aware that _overloading_ `exit` does **not** work in Posix (or bash posix-mode). `exit` is a special built-in that will always be taken as is. Overloading by a function definition does not work! – kvantour Jun 30 '23 at 13:29
  • You could use `[[ -v TMUX ]]` instead of `[[ -n $TMUX ]]`. Just testing if variable exist! His content and even knowing if they contain something doesn't matter! – F. Hauri - Give Up GitHub Jun 30 '23 at 13:52