summary refs log tree commit diff stats
path: root/session.bash
diff options
context:
space:
mode:
authorSoniEx2 <endermoneymod@gmail.com>2022-01-15 16:00:39 -0300
committerSoniEx2 <endermoneymod@gmail.com>2022-01-15 16:00:39 -0300
commit2ba539f3685d95e8535dbd3a7d389c69739f1061 (patch)
tree8e4d00407ace33e1b8d75fb0eaa2ae533d8834ea /session.bash
Initial commit
Diffstat (limited to 'session.bash')
-rw-r--r--session.bash56
1 files changed, 56 insertions, 0 deletions
diff --git a/session.bash b/session.bash
new file mode 100644
index 0000000..caa35de
--- /dev/null
+++ b/session.bash
@@ -0,0 +1,56 @@
+# Copyright (C) 2021, 2022 Soni L.
+# SPDX-License-Identifier: AGPL-3.0-or-later
+
+# note: consider adding the following to your PS1:
+PS1='{$([[ "${HISTFILE#~/.bash_history.}" != "$HISTFILE" ]] && printf "@ " || printf "/ ")${HISTFILE#~/.bash_history.}} '"$PS1"
+
+if [[ "$HISTFILE" = ~/.bash_history ]]; then
+	HISTFILE="$HISTFILE".default
+fi
+
+# simple interface to history/"session" management
+# usage: session <name>
+# switches HISTFILE to ~/.bash_history.<name>
+session() {
+	if [[ "$1" =~ ^[a-z][a-z0-9]*$ ]]; then
+		# remove session switch from history
+		history -d -1
+		# write/append history
+		if shopt -q histappend; then history -a; else history -w; fi
+		# clear history
+		history -c
+		# set HISTFILE
+		HISTFILE=~/.bash_history."$1"
+		# load new session's history
+		history -r
+		# see setsessioncwd()
+		eval "$(grep -s '# '"$1"'$' ~/.bash_session_cwd | tail -n 1)"
+	else
+		echo "invalid session"
+		false
+	fi
+}
+
+# sets the current cwd as the default cwd for the session
+setsessioncwd() {
+	local session
+	# guard against relative HISTFILE
+	if [[ "${HISTFILE#~/.bash_history.}" != "$HISTFILE" ]]; then
+		session="${HISTFILE#~/.bash_history.}"
+		if [[ "$session" =~ ^[a-z][a-z0-9]*$ ]]; then
+			printf 'cd %q # %s\n' "$PWD" "$session" >>~/.bash_session_cwd
+		else
+			echo "invalid session"
+			false
+		fi
+	else
+		echo "invalid session"
+		false
+	fi
+}
+
+# saves the current working directory into the current history.
+# does NOT save to the history *file*.
+savecwd() {
+	history -s "$(printf 'cd %q' "$PWD")"
+}