This repository has been archived on 2024-03-04. You can view files and clone it, but cannot push or open issues or pull requests.
linux/.config/bash/module/Cd.sh

60 lines
1.3 KiB
Bash
Raw Normal View History

2024-01-09 19:53:36 +03:00
# CD (back to) directory.
# Goes to the exact-match dir first. If no exact match found, it finds first directory that contains the input (case-insensitive).
# Usage: cdd <DIR>
2023-12-07 01:44:42 +03:00
function cdd() {
2023-12-05 21:50:45 +03:00
local target="${1}"
2024-01-09 19:53:36 +03:00
if [[ "${target}" = "" ]]; then
help cdd
return 2
fi
local array=($(_cdd_directories))
2023-12-05 21:50:45 +03:00
local result
2024-01-09 19:53:36 +03:00
# Check for exact match ELSE look for containing.
if _contains ${target} ${array[@]}; then
local current="${PWD%/*}"
result="${current%\/$target\/*}/${target}"
else
# Make search case-insensitive.
shopt -s nocasematch
2024-01-09 19:53:36 +03:00
# Find dir name that contains input.
local found=1
for (( idx=${#array[@]}-1 ; idx>=0 ; idx-- )); do
dir="${array[idx]}"
[[ "${dir}" =~ "${target}" ]] && found=0
[[ ${found} = 0 ]] && result="/${dir}${result}"
done
2024-01-09 19:53:36 +03:00
# Clean-up???
shopt -u nocasematch
fi
2023-12-05 21:50:45 +03:00
# Go there!
if [[ "${result}" != "" ]]; then
echo "${result}"
cd "${result}"
else
return 1
fi
}
2023-12-14 22:06:49 +03:00
2024-01-09 19:53:36 +03:00
# Get list of all parent dirs.
function _cdd_directories() {
2023-12-14 22:06:49 +03:00
local array
IFS='/' read -r -a array <<< "${PWD}"
array=("${array[@]:1}")
unset array[-1]
2024-01-09 19:53:36 +03:00
printf "%s\n" "${array[@]}"
}
function _comp_cdd() {
local IFS=$'\n'
local dirs=($(_cdd_directories))
_autocomplete_first ${dirs[@]}
2023-12-14 22:06:49 +03:00
}
2024-01-09 19:53:36 +03:00
complete -o nosort -o filenames -F _comp_cdd cdd