2

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

4 Answers 4

6

$_ 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)

5

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.

1
  • And ! 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
2

Pressing Esc + . places the last argument of previous command on the current place of cursor. Tested in bash shell and ksh shell.

1
  • 1
    Different effects depending on 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)
    – cdarke
    Commented Sep 12, 2012 at 13:43
1

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).

2
  • .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.
    – chepner
    Commented Sep 12, 2012 at 13:48
  • This will work on at least openSUSE and Ubuntu (so it should work on Debian, too). Commented Sep 12, 2012 at 13:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.