Search code examples
shellcommand-linecommandconfiguration-files

How can I have a variable command name to be interpreted and executed in shell configuration file?


I have seen experts do something like:

>> -5

which jumps them up 5 levels of parent directories.

I'm like: "This is so cool!"

I am able to add this in my shell configuration file, but not in a very concise manner.

What I've done is add this to my .zshrc (works with .bashrc or other shells also) configuration file.

function -1 {
  cd ..
}
function -2 {
  cd ../..
}
function -3 {
  cd ../../..
}

This works.

Of course, what if I want to do -25? I probably wouldn't bother counting that much, but you never know. You can see how this would get lengthy. I want to avoid copy-paste type bad coding practices.

I've tried adding:

function "$0" {
#...

or

function "$@" {
#...

To try and grab the command input. I am hoping I could then use regex to find the string, parse, make a loop for the value for any number of parent levels... I have code for this but am struggling with this first step:

The "$@" type commands don't work at all... even if it did, I'm not sure I want all commands to hit this block and not have the nice zsh: <command provided>: command not found... error message appear. Is there any way to avoid this?

This all boils down to having variable command names. Maybe this is the better question: is it even possible?

I'm sure someone has thought of this. I tried looking it up but haven't found anything yet.


Solution

  • See below bash/zsh solution. Using the "evil eval" :-) Works for bash (5.1.6), and zsh (5.8.1)

    dd=..
    for ((x=1 ; x<=25 ; x++)) { eval "function -$x { cd $dd ; }" ; dd+=/.. ; }
    

    May also work on other sh-like program with minor modification.