Last active
July 1, 2025 12:07
-
-
Save 4msar/a26356c809cf61e6d5899298049d565e to your computer and use it in GitHub Desktop.
Folder bookmark system with bash script. Read the article: https://blog.msar.me/create-a-folder-bookmarking-system-in-bash-with-goto-and-bookmark-commands
This file contains hidden or 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 | |
# file: .bookmark | |
# Bookmark storage file | |
BOOKMARKS_FILE="$HOME/.folder_bookmarks" | |
# Save current directory with a name | |
bookmark() { | |
local name="$1" | |
if [ -z "$name" ]; then | |
echo -n "Enter bookmark name: " | |
read name | |
fi | |
if [ -z "$name" ]; then | |
echo "Bookmark name cannot be empty." | |
return 1 | |
fi | |
mkdir -p "$(dirname "$BOOKMARKS_FILE")" | |
# Remove any existing entry with the same name | |
grep -v "^$name|" "$BOOKMARKS_FILE" 2>/dev/null > "${BOOKMARKS_FILE}.tmp" | |
mv "${BOOKMARKS_FILE}.tmp" "$BOOKMARKS_FILE" | |
# Save the new bookmark | |
echo "$name|$PWD" >> "$BOOKMARKS_FILE" | |
echo "Bookmarked '$PWD' as '$name'" | |
} | |
# Navigate to a bookmarked directory | |
goto() { | |
local name="$1" | |
if [ ! -f "$BOOKMARKS_FILE" ]; then | |
echo "No bookmarks found." | |
return 1 | |
fi | |
local dir | |
if [ -n "$name" ]; then | |
dir=$(grep "^$name|" "$BOOKMARKS_FILE" | cut -d'|' -f2) | |
if [ -z "$dir" ]; then | |
echo "Bookmark '$name' not found." | |
return 1 | |
fi | |
else | |
# Interactive prompt using fzf | |
local selection | |
selection=$(awk -F '|' '{ printf "%s\t%s\n", $1, $2 }' "$BOOKMARKS_FILE" | fzf --prompt="Goto bookmark: " --with-nth=1) | |
if [ -z "$selection" ]; then | |
echo "No selection made." | |
return 1 | |
fi | |
dir=$(echo "$selection" | cut -f2) | |
fi | |
if [ -d "$dir" ]; then | |
cd "$dir" | |
else | |
echo "Directory does not exist: $dir" | |
fi | |
} | |
# Autocomplete function for goto | |
_goto_complete() { | |
local cur_word bookmarks | |
cur_word="${COMP_WORDS[COMP_CWORD]}" | |
if [ -f "$BOOKMARKS_FILE" ]; then | |
bookmarks=$(cut -d'|' -f1 "$BOOKMARKS_FILE") | |
COMPREPLY=( $(compgen -W "$bookmarks" -- "$cur_word") ) | |
fi | |
} | |
# Register autocomplete for goto | |
complete -F _goto_complete goto |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation
.bookmark
in your home directory.~/.bashrc
or~/.zshrc