如何在命令行中获得前一个命令的第 n 个参数? [英] How do you get nth argument of a previous command at command line?

查看:16
本文介绍了如何在命令行中获得前一个命令的第 n 个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在交互式 shell 中输入以下内容:

If you're at an interactive shell and you type something like:

echo this is it

然后你可以展开第一个参数:

Then later you can expand the first argument:

echo !^    #=> echo this

或者你可以扩展最后一个参数:

Or you can expand the last argument:

echo !$    #=> echo it

但现在我想知道:

我将如何访问第 n 个参数?我查看了一个相关的bash问题,但似乎只有在脚本中才有效,因为!n 只是浏览我的命令历史(而不是我的参数历史) - 例如

How would I access the nth argument? I looked through a related bash question, but it seems like that only works when in a script, because !n just goes through my command history (instead of my argument history) - for example

    echo !1 #=> echo ls

这是有道理的,因为

    history | grep -E '^\s+1 ' #=> 1  ls

但我想要的是 echo !(一些正确的索引)#=>回声是

推荐答案

这样:

~ $ echo this is it
~ $ echo !!:2
echo is
is

!!:n 是第 n 个参数
!!:n-$ 是从第 n 到最后的参数

!!:n is the n'th arg
!!:n-$ is args from n'th to last

注意:!! 扩展到最后一个命令<小时>根据 OP 的编辑(已移动):

Note: !! expands to the last command


As per OPs' EDIT (moved):

倒数第二个命令的第二个参数:

Second argument of the second to last command:

~ $ echo foo bar baz # This one is the target
foo bar baz
~ $ echo catz ratz batz
catz ratz batz
~ $ echo !-2:2
echo bar
bar

!-n 扩展为在当前命令之前有 'n' 个命令的命令.

!-n expands to the command that was 'n' number of commands before the current command.

注意:!-1!! 是一样的.

Note: !-1 and !! are the same.

这篇关于如何在命令行中获得前一个命令的第 n 个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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