interactivetmuxzshrc.profile

Prompt in .zshrc


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.)


Solution

  • 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.)