如何为命令"cd〜1"创建bash别名. [英] How to create an bash alias for the command "cd ~1"

查看:64
本文介绍了如何为命令"cd〜1"创建bash别名.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在BASH中,我使用"pushd."命令将当前目录保存在堆栈中.在几个不同的目录中发出此命令后,我在堆栈上保存了多个目录,可以通过发出命令"dirs"看到这些目录.例如,下面是我当前bash会话中"dirs"命令的输出-

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

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

现在,要切换到第0个目录,我发出命令"cd〜0".我想创建一个bash别名命令或该命令的函数.诸如"xya 0"之类的东西,它将切换到堆栈上的第0个目录.我写了以下函数来实现这一目的-

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
}

xya(){
cd ~$1
}

上面函数中的"$ 1"是传递给函数"xya"的第一个参数.

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

但是,我收到以下错误-

But, I am getting the following error -

-bash:cd:〜1:没有这样的文件或目录

你能告诉我这里出了什么问题吗?

Can you please tell what is going wrong here ?

推荐答案

通常,bash解析按以下顺序进行:

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

因此,到您扩展参数时,代字号扩展已经完成并且不会再次发生,而无需进行明确的操作,例如使用 eval .

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.

如果您知道风险并愿意接受,请使用 eval强制解析在 $ 1 扩展完成之后从头开始.如果将 eval -safe以外的内容作为参数传递,则下面的示例尝试减轻损害:

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

...或者,不太谨慎(也就是说,以下内容相信您的参数是 eval -safe):

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

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

这篇关于如何为命令"cd〜1"创建bash别名.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆