markhuge

Spawn Term If Needed

Published by Mark on

If you use a launcher like dmenu or hotkeys to launch scripts, anything you invoke will have a $TERM of “linux”.

By adding a guard for this value, you can tell whether or not you’re running inside of a terminal, and if not, run the script inside your terminal of choice:

#!/bin/sh

if [ "$TERM" = 'linux' ]; then
  st -e "$0"
else
  do stuff ...
fi

Example

  1. Open in the current terminal
  2. or, if not currently in a terminal, launch one and run this from there
  3. Create a new named tmux session, or attach to the session if it already exists
#!/bin/sh

if [ "$TERM" = 'linux' ]; then
  st -e "$0"
else
  SESSION=media
  if ! tmux has-session -t $SESSION 2>/dev/null; then
    tmux new-session -d -s $SESSION -n 'rss' newsboat
    tmux new-window -d -t $SESSION:1 -n 'mp3' pms
  fi
  tmux attach -t $SESSION
fi

I use this pattern all the time. As a matter of fact, I’m using it to write the blog entry:

#!/bin/sh

if [ "$TERM" = 'linux' ]; then
  st -e "$0"
else
  SESSION=blog
  BLOGPATH="${CODEPATH}/blog"

  if ! tmux has-session -t $SESSION 2>/dev/null; then
    cd "${BLOGPATH}" || exit 2
    tmux new-session -d -s $SESSION
    tmux new-window -d -t $SESSION:1 -n 'hugo-server' hugo server --buildDrafts

    $BROWSER http://localhost:1313 &
  fi
 tmux attach -t $SESSION
fi