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

拈花ヽ惹草 提交于 2021-02-10 14:19:57

问题


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 ?


回答1:


Generally, bash parsing happens in the following order:

  • brace expansion
  • tilde expansion
  • parameter, variable, arithmetic expansion; command substitution (same phase, left-to-right)
  • word splitting
  • pathname expansion

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"
}



回答2:


You can let dirs print the absolute path for you:

xya(){
    cd "$(dirs -${1-0} -l)"
}


来源:https://stackoverflow.com/questions/58475460/how-to-create-an-bash-alias-for-the-command-cd-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!