I love terminals. Every day, I can have 5 or 10 of them open at the same time. Indeed, they can be used to program (for example you have one open inside VScode) a backend and a frontend, but also to do some git stuff, launch AI agents, etc.
The problem, however, when you open a new terminal every 10 minutes, is that you have to manually cd s/my-forge/my-project/my-repository/src every single time. And as terminals are quite ephemeral, this gets old fast.
about cons
So the idea is to store the last working directory of every terminal.
In Linux (maybe UNIX?), every terminal has a unique file descriptor that you can access through the tty binary1:
$ tty
/dev/pts/3
Then, we can tell bash (or your preferred shell), to store its current working directory. I decided to store them in /dev/shm/cons_$USER:
# Where console history is stored
CONS_ROOT_DIRECTORY="${CONS_ROOT_DIRECTORY:-/dev/shm/cons_$USER}"
# Ensure storage exists
_cons_ensure_root() {
[[ -d "$CONS_ROOT_DIRECTORY" ]] || mkdir -p "$CONS_ROOT_DIRECTORY"
}
# Save current directory for current TTY
cons_set() {
_cons_ensure_root
local tty_no
tty_no="$(tty | awk -F/ '{print $NF}')"
pwd > "$CONS_ROOT_DIRECTORY/$tty_no"
}
# Store current directory + ls at the end
cd() {
local last="$PWD"
if [[ $# -eq 0 ]]; then
builtin cd ~ || return
else
builtin cd -- "$*" || return
fi
cons_set >/dev/null
ls
}
With this, every time you cd to a directory, the path is stored to /dev/shm/cons_$USER/$tty2.
The next step is to be able to retrieve this list:
# List or jump to stored directories (unique)
cons() {
_cons_ensure_root
# Jump to entry
if [[ $# -eq 1 ]]; then
local target="$CONS_ROOT_DIRECTORY/$1"
[[ -f "$target" ]] || { echo "$1 does not exist"; return 1; }
builtin cd -- "$(cat "$target")" || return
cons_set
ls
return
fi
# Show unique directories only
local file dir
declare -A seen
for file in "$CONS_ROOT_DIRECTORY"/*; do
[[ -f "$file" ]] || continue
dir="$(<"$file")"
# skip duplicates
[[ -n "${seen[$dir]}" ]] && continue
seen["$dir"]=1
printf "%s >>\n\t%s\n" "$(basename "$file")" "$dir"
done
}
The end result:
✔️ 23:11:49 ~$
⇶ cons
0 >>
/home/frank/s/forge.k3s.fr/sisol/backend
1 >>
/home/frank/s/forge.k3s.fr/frank/website
10 >>
/dev/shm
5 >>
/home/frank/s/forge.k3s.fr/k8sinfra/gitops
7 >>
/tmp
✔️ 23:11:49 ~$
⇶ cons 1
archetypes content hugo.toml layouts public static themes
✔️ 23:11:55 (article-cons)~/s/forge.k3s.fr/frank/website
⇶
With this, when I need to open a new terminal and go to my project directory, I just cons-it, and there it is :-)
Cheers
Behind the scenes,
ttyjust reads/proc/self/fd/0, which is basically the standard out put of itself, which is generally linked to the terminal, and thus/dev/pts/xxx↩︎Why
/dev/shm? Usually it was mounted as aramfsdevice, which meant that it was stored in ram (no useless disk writes), and thus would clear upon restart. I guess now that doesn’t make much sense, and even a user local directory could be used ↩︎