1

This is a situation I often find myself in:

mkdir /Some/really/long/path/to/a/directory/
cd /Some/really/long/path/to/a/directory/

I know that ideally you would cd /Some/...etc.../a/ and then mkdir directory, but I've often performed mkdir first and then had to cd to the end of the same lengthy file path I just created.

Short of doing...

var="/Some/...etc.../a/"
mkdir $var/directory; cd $var

...which is even worse, is there some way to reuse the parameter passed to the previous command? I'm aware of course of tab completion, but in a series of nested directories with similar names this doesn't always help that much. Ideally, I'm hoping for a shortcut like $# or $@.

Failing this, the next best time-saving solution would be equally appreciated!

toxefa
  • 1,103

3 Answers3

3

There are previous answers that suggest you to use $_ and !$. While this works, I find it quite dangerous as they are not expanded and you cannot see their value before pressing enter and executing the command. Imagine using rm $_ without being sure what you're going to delete!

If you're using bash (probably with readlines's emacs mode, which is the default), I suggest you to press ESC, release it, and then press ..

This shortcut recalls the last argument from the last executed command. So writing cd <ESC> <.> will bring you your long path/file.

The hotkey ALT + . (pressed simultaneously) works in the same way.

If you're using bash vi mode instead of the default's emacs mode, you can simulate this behaviour with ALT + . if you alter your ~\.inputrc file with:

set keymap vi-insert

$if mode=vi
    "\e.": yank-last-arg
$endif
sromero
  • 757
  • 5
  • 11
2

In bash (and some other shells, like zsh), you can use $_, which contains the last argument to the previous command:

mkdir /path/to/file
cd "$_"
Chris Down
  • 125,559
  • 25
  • 270
  • 266
2

When working interactively, you can use history expansion for this:

mkdir /Some/really/long/path/to/a/directory/
cd !$

There are loads of variants to this which allow you to access other parameters from the previous command or any other command in your history. See Bash, insert last used argument of current command for details...

Stephen Kitt
  • 434,908