Skip to content

Instantly share code, notes, and snippets.

@Genzer
Created January 16, 2024 08:53
Show Gist options
  • Save Genzer/218dd4fb30cbcc8ed64fab5a7d0408ea to your computer and use it in GitHub Desktop.
Save Genzer/218dd4fb30cbcc8ed64fab5a7d0408ea to your computer and use it in GitHub Desktop.
Quicker than typing cd ..
#!/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 "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment