0

When I start my terminal emulator, it either creates a new tmux session (named $(whoami)) or, if it already exists, attaches to that. However, I would like the ability to choose to create a new session if there is already one active.

The previous behaviour was part of my .zshrc script, so I figured I could put the extra logic in there. This is what I came up with in a separate script:

sessions=$(tmux list-sessions -F "#{session_created},#S")
sessionCount=$(echo "$sessions" | wc -l)

if (( $sessionCount > 0 )); then
  now=$(date +%s)

  echo -e "Attach to an existing session, or start a new one:\n"

  # List sessions in reverse chronological order
  echo "$sessions" | sort -r | while read line; do
    created=$(cut -f1 -d, <<< $line)
    session=$(cut -f2 -d, <<< $line)
    age=$(bc <<< "obase=60;$now - $created" | sed "s/^ //;s/ /:/g")
    echo -e "\t\x1b[1;31m$session\x1b[0m\tcreated $age ago"
  done

  echo
  read -p "» " choice
else
  # Default session
  choice=$(whoami)
fi

exec tmux -2 new-session -A -s $choice

Modulo the session attachment, this works. However, this doesn't work when it's put in my .zshrc. The read line gives an error:

read: -p: no coprocess

What's the problem?

(This is under OS X, if that makes a difference.)

Xophmeister
  • 8,884
  • 4
  • 44
  • 87

1 Answers1

3

read -p "» " choice is bash syntax for displaying a prompt before waiting for user input. In zsh, the equivalent is

read 'choice?» '

(That is, one word consisting of the variable name and the prompt joined by a ?. The whole thing is quoted, although really only the ? needs to be to prevent zsh from interpreting the word as a pattern.)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks: I had just found this out by reading the `zshbuiltins` man page, but you beat me to the answer :) – Xophmeister Jul 02 '15 at 20:25
  • 1
    Bonus `zsh` tip: `${#${(f)sessions}}` will give you the session count without having to call `wc`. :) – chepner Jul 02 '15 at 20:36
  • Having read the man page for zsh's `read`, there is another trick I can do to simplify this script. Specifically, the calls to `cut` can be removed if the while loop is changed to `while IFS="," read created session` – Xophmeister Jul 02 '15 at 21:26