bashpushd

How to create an bash alias for the command "cd ~1"


In BASH, I use "pushd . " command to save the current directory on the stack. After issuing this command in couple of different directories, I have multiple directories saved on the stack which I am able to see by issuing command "dirs". For example, the output of "dirs" command in my current bash session is given below -

0 ~/eclipse/src
1 ~/eclipse
2 ~/parboil/src

Now, to switch to 0th directory, I issue a command "cd ~0". I want to create a bash alias command or a function for this command. Something like "xya 0", which will switch to 0th directory on stack. I wrote following function to achieve this -

xya(){
cd ~$1
}

Where "$1" in above function, is the first argument passed to the function "xya".

But, I am getting the following error -

-bash: cd: ~1: No such file or directory

Can you please tell what is going wrong here ?


Solution

  • Generally, bash parsing happens in the following order:

    Thus, by the time your parameter is expanded, tilde expansion is already finished and will not take place again, without doing something explicit like use of eval.


    If you know the risks and are willing to accept them, use eval to force parsing to restart at the beginning after the expansion of $1 is complete. The below tries to mitigate the damage should something that isn't eval-safe is passed as an argument:

    xya() {
      local cmd
      printf -v cmd 'cd ~%q' "$1"
      eval "$cmd"
    }
    

    ...or, less cautiously (which is to say that the below trusts your arguments to be eval-safe):

    xya() {
      eval "cd ~$1"
    }