markhuge MH\n s

Spawn Term If Needed

published:

signed with 0x683A22F9469CA4EB

tags:

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

About the Author

Mark Wilkerson

0x683A22F9469CA4EB

R&D engineer @ Twitch. Previously Blizzard, Hightail, Co-Founder @ SpeakUp

Mark is building open source tools to make web3 and decentralized self-ownership easy for regular people.

Live dev streams at Twitch.tv

More Posts