banner

For a full list of BASHing data blog posts see the index page.     RSS


How to bookmark directories in the shell

Most of the work I do in Gnome Terminal is with files downloaded from the Web to my desktop. For this reason I have an alias, "desk"...

alias desk='cd ~/Desktop'

...in my "~/.bashrc" file so I can quickly switch to the desktop from the default working directory, "/home/bob". However, I also do shell work on files in other directories scattered around my file system. It would be nice to bookmark a directory when I'm in it, so I can return to it quickly the next time I open a terminal. Gnome Terminal, unfortunately, doesn't have a bookmarking feature.

After googling around for solutions, I decided it would be easier to build my own bookmarker, one that was portable between computers and terminal programs. The result is described below, and I'm again very grateful to BASH wizard Chris Dunlop of onthe.net.au for his advice on how to improve the code.


Bookmarking. When I'm working in the shell and I decide to bookmark the current directory, I enter book, a function defined in "~/.bashrc":

book() { printf "$(pwd)\n" | sed 's|/home/bob/||' >> ~/scripts/workplaces; }

The command takes the path of the current directory from the pwd command, clips off the string "/home/bob/" with sed and appends the remiander of the path to the text file "workplaces" in my "scripts" directory. Here's today's "workplaces":

bookmark1

I like the idea of keeping the bookmark list in a separate text file, as I can edit it either in the shell or in a text editor. Editing will be necessary if the list gets too long, because my bookmark-picker (below) can only handle up to nine bookmarks.


Picking a bookmark. The function goto, another "~/.bashrc" resident, is shown below.

function goto
{
local foo=$(sort ~/scripts/workplaces | nl -w1)
local REPLY
echo -e "\n0\tquit\n$foo\n"
read -p "Enter a directory number: "
if [[ $REPLY =~ ^[0-"$(echo "$foo" | wc -l)"]$ ]]; then
[[ $REPLY = "0" ]] && return
cd "/home/bob/$(grep ^$REPLY <<<$foo | cut -f2)" && echo "Now in $(pwd)"
else
echo "No such number"
fi
}

When I enter goto I'm presented with a sorted and numbered list from "workplaces", with an added "0" option to quit:

bookmark2

Choosing a number from the list (other than zero) and entering it takes me back to a prompt, after a message appears with the new current directory. As pwd shows in the screenshot below, I've indeed moved to the directory I selected:

bookmark3

Entering anything other than a number in the range from "0" to the number of lines in "workplaces" (^[0-"$(echo "$foo" | wc -l)"]$) returns a "No such number" message:

bookmark4

Because I've used a digit range in the regex, I can only select a number from "0" up to "9" ([0-9]) with goto, but nine is enough in my work.


Last update: 2020-06-10
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License