我可以让 shell 别名评估历史替换命令吗?
我正在尝试为 cd !!:1 编写一个别名,它采用上一个命令的第二个单词,并更改为该名称的目录。例如,如果我输入
rails new_project
cd !!:1
第二行,则会 cd 进入“new_project”目录。
由于 !!:1 很难输入(尽管它很短,但它需要键盘两侧的三个 SHIFT 键,然后是按两次 SHIFT 键输入的未 SHIFT 版本的键),所以我只想输入一些内容就像
cd-
但由于 !!:1 是在命令行上评估的,我(显然)不能这样做
alias cd-=!!:1
,否则我会保存一个包含硬编码到其中的“new_project”的别名。所以我尝试了
alias cd-='!!:1'
这个问题是 !!:1 从未被评估,并且我收到一条消息,表示不存在名为 !!:1 的目录。如何创建一个别名,其中历史替换在我发出别名命令时评估,而不是在我定义别名时评估,而不是从不评估?
(我已经在 bash 和 zsh 中尝试过此操作,并在两者中得到相同的结果。)
I'm trying to write an alias for cd !!:1, which takes the 2nd word of the previous command, and changes to the directory of that name. For instance, if I type
rails new_project
cd !!:1
the second line will cd into the "new_project" directory.
Since !!:1 is awkward to type (even though it's short, it requires three SHIFTed keys, on opposite sides of of the keyboard, and then an unSHIFTed version of the key that was typed twice SHIFTed), I want to just type something like
cd-
but since the !!:1 is evaluated on the command line, I (OBVIOUSLY) can't just do
alias cd-=!!:1
or I'd be saving an alias that contained "new_project" hard-coded into it. So I tried
alias cd-='!!:1'
The problem with this is that the !!:1 is NEVER evaluated, and I get a message that no directory named !!:1 exists. How can I make an alias where the history substitution is evaluated AT THE TIME I ISSUE THE ALIAS COMMAND, not when I define the alias, and not never?
(I've tried this in both bash and zsh, and get the same results in both.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 bash:
For bash:
完成同样事情的另一种方法:
对于最后一个参数:
或
对于第一个参数:
或
Another way to accomplish the same thing:
For the last argument:
or
For the first argument:
or
对于 zsh:
这是如何工作的:
$(fc -l -1)
。fc -l {start} [{end}]
表示“列出从 {start} 到 {end} 的历史命令,或者如果 {end} 不存在则列出最后一个命令”。${(z)...}
必须将...
拆分为一个数组,就像 shell 所做的那样(请参阅man zshexpn< 中的“参数扩展标志” /code>),但实际上它是在空格上分割的。也许这只是我的错误。
${...[3]}
从数组中获取第三个值。第一个值是命令的编号,第二个是命令,第三个及后面的值是参数。For zsh:
How this works:
$(fc -l -1)
is evaluated.fc -l {start} [{end}]
means «list history commands from {start} till {end} or last if {end} is not present».${(z)...}
must split...
into an array just like the shell does (see «Parameter Expansion Flags» inman zshexpn
), but in fact it splits on blanks. Maybe it is only my bug.${...[3]}
takes third value from the array. First value is a number of a command, second is command and third and later are arguments.