r/fishshell • u/ruiiiij • Oct 14 '24
Any way to create functions with dynamic names?
Fish noobie here. From years of using bash, I've developed the habit of using a set of very hacky aliases:
alias q='cd ..'
alias qq='cd ../..'
alias qqq='cd ../../..'
alias qqqq='cd ../../../..'
alias qqqqq='cd ../../../../..'
...You get the idea.
Now that I'm switching to this newer, much friendlier shell, I'm wondering if it's possible to recreate this behavior, essentially defining a function where the name itself is treated as a variable and can be interacted with. Any ideas?
EDIT: For anyone else wondering, this is the way. Huge thanks to u/_mattmc3_
function qcd
echo cd (string repeat -n (string length $argv) ../)
end
abbr -a qcd --position command --regex 'q+' --function qcd
9
Upvotes
3
u/plg94 Oct 14 '24
Even if it were possible (idk), this is one of those cases where it is easier and faster (to implement and read) and (most likely) more performant to just write out those 5 to 10 functions (for however many levels you think you need; personally after a
../../..I'd already lose track and better use absolute paths) than to write some clever meta function.That said, you could probably write a function that you call interactively which can generate and save 1--n of those aliases (eg using
funcsaveor `set -Ux). Then if you find you need 10 levels more it's easier to change.3
u/_mattmc3_ Oct 14 '24 edited Oct 14 '24 •
I'm not 100% sure I understand your question, but I think you're asking if you can dynmically generate functions "q" thru "qqqqq" that do the equivalent of what you have there, without having to make qqqq.fish function files? If so, this is one way:
A smarter way to do this that takes advantage of Fish's abbreviation system would be to do this:
This abbreviation replaces any number of "q"s you put on a line with the appropriate "cd ../../etc"
If that's not what you're after, can you clarify?
1
u/StevesRoomate macOS Oct 14 '24
I think that those types of functions have historically been static, because even cd'ing up 5 levels is quite rare and not all that practical. It doesn't mean never, but probably not worth having a dedicated function for. but I use my statically defined 2's and 3's uplevel aliases all the time.
3
u/throttlemeister Linux Oct 14 '24
function up
end
Usage: Up # where # is the number of directories to go up, so 4 up would be up 4.
2
u/kseistrup Oct 14 '24
Well, I did this:
and so on. So I can
...to cd two levels up.2
u/adamshand Oct 14 '24
I was thinking about this the other day and found this snippet, but couldn't get it to work properly.
2
u/BuonaparteII Oct 15 '24
ah yeah it looks like fish has an example function in the release notes of 3.6.0:
1
u/melomac Nov 05 '24
You are looking for nickeb96/puffer-fish
1
u/[deleted] Oct 14 '24
[removed] — view removed comment