Skip to content

Instantly share code, notes, and snippets.

@ajitid
Last active July 29, 2021 14:24
Show Gist options
  • Save ajitid/001c83ffc22247918096ea6722133687 to your computer and use it in GitHub Desktop.
Save ajitid/001c83ffc22247918096ea6722133687 to your computer and use it in GitHub Desktop.
πŸ‘ Butt - Target a dir in PWD

Usage

Given $PWD is /home/a-user/ghq/github.com/gh-user/project/src, butt ghq will change your $PWD to /home/a-user/ghq/. Press cd - to get back where you were before.

Note: If your usecase demands this script, I would suggest to use z like dir jumpers instead.

function butt
if [ "$argv[1]" = "" ]
echo "Please provide a dir name"
return 1
end
set -l up_times 0
set -l found 0
set -l path (string sub --start 2 $PWD)
for i in (echo $path|awk -F'/' '{for(i=1;i<=NF;++i)print $i}')[-2..1]
set up_times (math "$up_times+1")
if [ "$i" = "$argv[1]" ]
set found 1
break
end
end
if [ "$found" = 1 ]
set -l alt_dir $PWD
while test "$up_times" -gt 0;
cd ..;
set up_times (math $up_times - 1);
end
set -l cur_dir $PWD
cd $alt_dir
cd $cur_dir
else
echo "Couldn't find the dirname you passed in PWD"
return 2
end
end
@ajitid
Copy link
Author

ajitid commented Jul 29, 2021

This could be a simpler solution https://news.ycombinator.com/item?id=27994905

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment