/tmux-launch.sh Secret
Last active
April 3, 2024 21:11
tmux multi-pane window launcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
loc=$(dirname $0) | |
me=$(basename $0) | |
PS4='+(${BASH_SOURCE}:${LINENO}):${FUNCNAME[0]:+${FUNCNAME[0]}()}: ' | |
# process command line options | |
NUM=0 | |
HORIZONTAL=0 | |
TILED=0 | |
VERBOSE=":" | |
while getopts Hhn:Tv option; | |
do | |
case "$option" | |
in | |
H) HORIZONTAL=1;; | |
n) NUM=$OPTARG;; | |
T) TILED=1;; | |
v) VERBOSE="set -x";; | |
h) cat <<EOF >&2 | |
USAGE: ${me} [options] SESSION DIR:[CMD] [DIR:[CMD]] ... | |
-h display this help | |
-n <NUM> launch <NUM> panes in the first specified directory, DIR | |
-H horizontal split instead of the default vertical split | |
-v enable verbose output | |
[DIR] one or more startup directories; at least one is required | |
[CMD] optional command string associated with DIR; this can contain multiple commands if quoted | |
EOF | |
exit 2 | |
;; | |
esac | |
done | |
shiftcount=`expr $OPTIND - 1` | |
shift $shiftcount | |
# ------------------------------------------------------------------------------- | |
if [[ -z $2 ]]; then | |
current=$(tmux display -p "#S") | |
echo -e "\n *** ERROR: missing arguments. ***" | |
$0 -h | |
if [[ -n $current ]]; then | |
echo -e "current session: $current\n" | |
fi | |
exit 1 | |
else | |
session="$1" | |
shift | |
fi | |
if [ ${NUM} -gt 0 ]; then | |
i=0 | |
while [ $i -lt ${NUM} ]; do | |
args[$i]=$1 | |
i=$(expr $i + 1) | |
done | |
else | |
args=( "$@" ) | |
fi | |
# echo ${arg[@]} | |
# start tmux | |
( ${VERBOSE}; tmux new-session -s $session -d ) | |
( ${VERBOSE}; tmux ls ) | |
i=1 | |
for e in "${args[@]}"; do | |
# capture directory and optional command from $e | |
d=$(echo $e | awk -F: '{print $1}') | |
c=$(echo $e | awk -F: '{print $2}') | |
if [ ! -d $d ]; then | |
echo WARNING: directory does not exist, $d >&2 | |
continue | |
fi | |
# Select pane $i, set dir to $d, run pwd | |
if [ $i -gt 1 ]; then | |
( ${VERBOSE}; tmux split-window -t $(expr $i - 1) ) | |
fi | |
( ${VERBOSE}; tmux select-pane -t $i ) | |
( ${VERBOSE}; tmux send-keys -t $i "cd $d" C-m ) | |
if [ -n "$c" ]; then | |
# execute optional command | |
( ${VERBOSE}; tmux send-keys -t $i "$c" C-m ) | |
fi | |
# equally-spaced | |
if [ ${HORIZONTAL} -ne 0 ]; then | |
( ${VERBOSE}; tmux select-layout even-horizontal ) | |
elif [ ${TILED} -ne 0 ]; then | |
( ${VERBOSE}; tmux select-layout tiled ) | |
else | |
tmux select-layout even-vertical | |
fi | |
i=$(expr $i + 1) | |
done | |
# Finished setup, attach to the tmux session! | |
( ${VERBOSE}; tmux attach-session -t $session ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment