Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

zsh

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

like image 288
mbigras Avatar asked May 17 '16 13:05

mbigras


People also ask

Which history shortcut can you use to reference the previous command arguments?

To insert previous arguments:Alt + . : insert last argument from last command.

How do you view the previous commands which you have already executed?

The simplest way to look through your recent commands is to use the up and down arrow keys on your keyboard to scroll through the previous commands. If you want to reissue a found command simply press the enter key.

Which is used to access arguments of the earlier command in C shell?

When a csh script is invoked, the special variable argv is set to the wordlist of arguments given on the command line. Thus, as alternatives to the special variables $1 , $2 and so on, csh scripts can use $argv[1] , $argv[2] , and so on to access command line arguments.

How do I go back to the previous line in CMD?

Type cd \ into the prompt to go back to the directory. If you need to navigate from a location back to the main command prompt, this command takes you back immediately.


1 Answers

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.

like image 74
Jahid Avatar answered Sep 27 '22 20:09

Jahid