# Tmux attach/create?

**URL:** <https://community.learnlinux.tv/t/tmux-attach-create/286>\
**Category:** Linux on Servers\
**Created:** [March 6, 2021, 12:07am UTC](https://community.learnlinux.tv/t/tmux-attach-create/286 "2021-03-06T00:07:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![memilanuk](https://community.learnlinux.tv/user_avatar/community.learnlinux.tv/memilanuk/32/126_2.png) [@memilanuk](https://community.learnlinux.tv/u/memilanuk)\
**Post date:** [March 6, 2021, 12:07am UTC](https://community.learnlinux.tv/t/tmux-attach-create/286/1 "2021-03-06T00:07:41Z")

</div>

Recently started using `tmux`, much like `screen` that I used ages ago.

Is there a flag/option for tmux that would join an existing session if it exists, but if not, create a new one? Or is that something that would have to be handled with shell scripting and/or aliasing?

Thanks!

---

<div class="post-metadata">

**Author:** ![ameinild](https://community.learnlinux.tv/letter_avatar_proxy/v4/letter/a/51bf81/32.png) [@ameinild](https://community.learnlinux.tv/u/ameinild)\
**Post date:** [March 6, 2021, 8:52am UTC](https://community.learnlinux.tv/t/tmux-attach-create/286/2 "2021-03-06T08:52:34Z")

</div>

Here is a small shell script called tmux-start that takes session name as an argument, and attaches to it if it exists, and creates a new session if it does not exits. You can then run this script from your .bashrc - again with a condition only to run outside tmux:

```auto
[[-n "$TMUX"]] && tmux-start

```

```
#!/bin/bash

# Tmux Startup Script
# Usage: tmux-start [session_name]
# If no session name is provided, default session name is used

# If script is run inside tmux, exit without doing anything
if [[-n "$TMUX"]]; then
  echo "Nested tmux sessions not supported!"
  exit 1
fi

# Name session to $1, or default if $1 is empty
if [[-z "$1"]]; then
  session="default"
else
  session="$1"
fi

# Check if session is already running
tmux has-session -t "$session" > /dev/null 2>&1
if [[$? -eq 0]]; then
# If already running, attach to it
  tmux attach -t "$session"
else
  tmux new-session -s "$session"
fi
```

---

<div class="post-metadata">

**Author:** ![jay](https://community.learnlinux.tv/user_avatar/community.learnlinux.tv/jay/32/649_2.png) [@jay](https://community.learnlinux.tv/u/jay)\
**Post date:** [March 13, 2021, 7:23pm UTC](https://community.learnlinux.tv/t/tmux-attach-create/286/3 "2021-03-13T19:23:27Z")

</div>

Awesome, thanks for sharing!
