grokking hard

code smarter, not harder

Goes back quicker in Terminal

Posted at — 2021-Mar-08

When I was working on a Terminal, I used to type lots of cd and cd .. to go back and forth the directory. Too often, when I went to deep into the directory hierarchy, I got to type multiple times cd .. just to move up to parents, or a long command like cd ../../../../../.

I got frustrated every freaking time doing this, so I thought of an more easy way to type once and it got me to the correct directory up in the hierarchy, I call the alias two-dots.

1
2
3
# Add this into your ~/.bashrc or ~/.zshrc
function back() { for x in {1..${1:-1}}; do cd ..; done }
alias ..='back'

How it works:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Suppose your are in
$> cd some/project/that/has/a/very/deep/directory/structure

structure $>

# Say you need to go back to 'that' directory.
# Normally, it requires 6 times typing "cd .." to achieve this.
$> .. 6

that $>

If you want to more enhanced version of back() such that typing .. 6 or .. that will produce the same result, you can check out my Gist:

#!/usr/bin/env bash
#----------
# back
# Goes back to parent directory quicker.
#
# NUMBER - goes back to x levels by repeatedly calling `cd ..`.
# SUBPATH - a segment of a full path to go back.
#
# *KNOWN LIMITS*
# - If the segment is a number, say 1234, use `back '/1234'`.
# - If there are more than one occurences of the segment in the full path,
# the first one will be used.
back() {
local target="${1:-1}"
local full_path="$(pwd)"
# If the argument is a number, treat it as how many level or parents
# to go back to.
if [[ "$target" =~ ^[[:digit:]].*$ ]]
then
for x in {1..${target}}
do
cd ..
done
return 0
else
# If the argument is not a number, test if it is a segment in the path
# of the current directory.
# If it is, then calculate the path to the argument and then
# simply cd to it.
if [[ "${full_path}" == *"${target}"* ]]
then
# Implementation note:
# Suppose the path is this/is/a/long/directory/path and the argument is `long`.
# First we need to find the path starting after the argument `directory/path` by
# using Bash Sub-string removal `${full_path##*target}`.
# Then we substract that path to the full path to have the path to the argument.
local trailing="${full_path##*${target}}"
local target_path="${full_path%${trailing}*}"
cd "${target_path}"
# cd "${full_path%${target}*}/${target}"
return 0
else
echo "error - cannot back to ${target} as it does not exist"
fi
return 1
fi
}
back "$@"
view raw back.sh hosted with ❤ by GitHub