Created
March 11, 2022 15:18
-
-
Save babarot/bebec3a4b19764021dca4022e007e266 to your computer and use it in GitHub Desktop.
tmux executor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# is_login_shell returns true if current shell is first shell | |
is_login_shell() { | |
[[ $SHLVL == 1 ]] | |
} | |
# is_git_repo returns true if cwd is in git repository | |
is_git_repo() { | |
git rev-parse --is-inside-work-tree &>/dev/null | |
return $status | |
} | |
# is_screen_running returns true if GNU screen is running | |
is_screen_running() { | |
[[ -n $STY ]] | |
} | |
# is_tmux_runnning returns true if tmux is running | |
is_tmux_runnning() { | |
[[ -n $TMUX ]] | |
} | |
# is_screen_or_tmux_running returns true if GNU screen or tmux is running | |
is_screen_or_tmux_running() { | |
is_screen_running || is_tmux_runnning | |
} | |
# shell_has_started_interactively returns true if the current shell is | |
# running from command line | |
shell_has_started_interactively() { | |
[[ -n $PS1 ]] | |
} | |
# is_ssh_running returns true if the ssh deamon is available | |
is_ssh_running() { | |
[[ -n $SSH_CLIENT ]] | |
} | |
main() { | |
# tmux_automatically_attach attachs tmux session automatically | |
is_ssh_running && return 0 | |
if is_screen_or_tmux_running; then | |
if is_tmux_runnning; then | |
export DISPLAY="${TMUX}" | |
elif is_screen_running; then | |
: # For GNU screen | |
fi | |
else | |
if ! is_ssh_running; then | |
if ! type tmux &>/dev/null; then | |
echo "tmux not found" 1>&2 | |
return 1 | |
fi | |
if tmux has-session &>/dev/null && tmux list-sessions | grep -qE '.*]$'; then | |
# detached session exists | |
tmux list-sessions | perl -pe 's/(^.*?):/\033[31m$1:\033[m/' | |
printf "tmux: attach? (y/N num/session-name) " | |
read | |
if [[ ${REPLY} =~ ^[Yy]$ || ${REPLY} == '' ]]; then | |
if tmux attach-session; then | |
echo "$(tmux -V) attached session" | |
return 0 | |
fi | |
elif tmux list-sessions | grep -q "^${REPLY}:"; then | |
if tmux attach -t "${REPLY}"; then | |
echo "$(tmux -V) attached session" | |
return 0 | |
fi | |
fi | |
fi | |
if type reattach-to-user-namespace &>/dev/null; then | |
# on OS X force tmux's default command | |
# to spawn a shell in the user's namespace | |
tmux_login_shell="${TMUX_SHELL:-/bin/zsh}" | |
tmux_config=$(cat ~/.tmux.conf <(echo 'set-option -g default-command "reattach-to-user-namespace -l' ${tmux_login_shell}'"')) | |
tmux -f <(echo "${tmux_config}") new-session && echo "$(tmux -V) created new session supported OS X" | |
else | |
tmux new-session && echo "tmux created new session" | |
fi | |
fi | |
fi | |
} | |
main "${@}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment