2

Would anyone have a user-defined function to put in my .basrc to do this. The following example should explain what I have in mind.

Given the following file system:

    Level1   Level2  Level3
  / TestA
~ - TestB   
  \ TestC  - TestB
           - TestD - CurrentLocation

Assuming the function is called goto.

goto(TestA): Should cd us to the level1 testA directory
goto(TestZ): Should keep us where we are and print something like "not found"
goto(TestB): Should bring us to level2 testB as its the closest.

The search should only ever go up and not down into parent directories as this may match multiple files.

Thanks

1
  • You might want to consider using zsh, it has a nice way of changing directories. For example from "CurrentLocation", you could do cd TestD TestB and would end up in ~/TestC/TestB/CurrentLoccation
    – Panki
    Aug 28 '19 at 11:03
0

Try this,

cdd(){
depth=$(pwd | tr -dc '/' | wc -c)
for ((d=0;d<=depth;d++)); do
    [ $d -eq 0 ] && search_dir="." || search_dir=$(printf '../%.0s' $(seq 1 $d))
    res=( )
    while IFS= read -r -d '' item; do
        res+=( "$item" )
    done < <(find $search_dir -mindepth 1 -maxdepth 1 -type d -name "$1" -print0)
    if [ ${#res[@]} -eq 0 ]; then
        continue
    elif [ ${#res[@]} -eq 1 ]; then
        t="$res"
    elif [ ${#res[@]} -gt 1 ]; then
        select t in "${res[@]}"; do
            break
        done
    fi
    echo "$t"
    cd "$t" && return || { echo "Unknown Error"; return; }
done
echo "Not found"
}

For each loop, it will search one more folder up the tree, until $depth is reached which is equivalent to the root folder /.

Usage: cdd targetname

Example:

$ cdd home
../../../home

If multiple directories found, it will present a select menu.

$ cdd "D*"
1) ../Documents
2) ../Downloads
3) ../Desktop
#? 2
../Downloads
3
  • Wow exactly what I was looking for and more! Tested it using a few directories and seemed to work perfectly! Greatly Appreciated, cheers
    – Ronan97
    Aug 28 '19 at 13:55
  • I improved the script a bit ... it had some issues.
    – pLumo
    Aug 28 '19 at 14:08
  • Hey pLumo, I am trying to extend this by chaining another function after it, to cd into the nearest child directory matching a given string. I am close but notice that it is not always giving my the nearst child and sometimes goes to very deep directories. cd "$(find . -type d -name <dir-name> -print -quit)"
    – Ronan97
    Aug 28 '19 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.