How do you get nth argument of a previous command at command line?

房东的猫 提交于 2019-12-04 19:32:38

问题


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

But now I'm wondering:

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

which makes sense, because

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

but what I want is echo !(some correct index) #=> echo is


回答1:


This way:

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

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

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 expands to the command that was 'n' number of commands before the current command.

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



来源:https://stackoverflow.com/questions/37277931/how-do-you-get-nth-argument-of-a-previous-command-at-command-line

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