how I can use the second argument of previous command in a new command ?
example, with
$ mkdir test
I make a directory, how I can use the name of directory for change to this ?
$ mkdir test && cd use_var
$_
is the last (right-most) argument of the previous command.
mkdir gash && cd "$_"
(I don't create files or directories called test
, that's the name of a shell built-in and can cause confusions)
With history expansion, you can refer to arbitrary words in the current command line
mkdir dir1 && cd "!#:1"
# 0 1 2 3 4
!#
refers to the line typed so far, and :1
refers to word number one (with mkdir
starting at 0).
If you use this in a script (i.e., a non-interactive shell), you need to turn history expansion on with set -H
and set -o history
.
!
refers to the previous line. !:1
is synonymous with !^
, and !$
is the last argument on the previous line.
Commented
Jan 9, 2014 at 0:22
Pressing Esc + . places the last argument of previous command on the current place of cursor. Tested in bash
shell and ksh
shell.
set -o emacs
(default in bash) and set -o vi
(default in ksh). In emacs editing mode it does as you say, in vi editing mode it repeats the whole of the previous statement. (tested in Bash 4 and ksh 93)
I use functions for this. Type this in your shell:
mkcd() { mkdir "$1" ; cd "$1" ; }
Now you have a new command mkcd
.
If you need this repeatedly, put the line into the file ~/.bash_aliases
(if you use bash
; other shells use different names).
.bash_aliases
is not automatically recognized by bash
, so you can put this in any file and make sure it is sourced by .bashrc
or .bash_profile
.