Is it possible to name a part of a command to reuse it in the same command later on?

You could do this:

mv /longpath/longfile !#:1:h/morepath/


  • !# is the current command
  • :1 is the first argument in this command
  • :h is the "head" -- think dirname
  • /morepath/ appends that to the head
  • and you're moving a file to a directory, so it keeps the same basename.

If you want to alter the "longfile" name, say add a ".txt" extension, you could

mv /longpath/longfile !#:1:h/morepath/!#:1:t.txt

Personally, I would cut and paste with my mouse. In practice I never get much more complicated than !! or !$ or !!:gs/foo/bar/

You could also do this with brace expansion:

mv /longpath/{,morepath/}longfile

The shell expands this so that the mv command sees it the same as:

mv /longpath/longfile /longpath/morepath/longfile

If you are for more efficient typing in command line, you may find various readline shortcut useful. Readline is already built-in your shell. For your paricular case you could yank/delete parts of your line and then recall them from readline killiring.

Moreover, if you have EDITOR environmnent variable set to your favorite editor, then Ctrl-X,Ctrl-E will copy your current command line into editor window where you can have all the editor power to modify your line. Once completed, you save/exit from the editor and the line gets executed in your shell.