Ubuntu – Change directory to target of move operation

command linemv

Occasionally, I have edited some file and want to move it to a different folder. (Typically: to a Dropbox folder, where I did not want to work to avoid giving the other owners of the folder constant updates.) I do this, for example, with

mv file.pdf ../../../Dropbox/sharedfolder/subdirectory/file.pdf

Afterwards, I often find myself wanting to change directory to the target directory of my previous move operation. I find myself hitting the up arrow, deleting the final file.pdf, holding left, deleting mv file.pdf and replacing it with cd.

Is there a faster, smarter way to do this? Is there a "move file and then change directory to" command, or a shortcut for the last used directory, or something like that?

Best Answer

If you're using bash, then its history interaction has just the shortcut for this. The word designator for the last argument of the previous command:

!!:$
designates the last argument of the preceding command. This may be shortened to !$.

Combined with a modifier to remove the last pathname component:

After the optional word designator, you can add a sequence of one or more of the valid modifiers, each preceded by a ‘:’.

h
Remove a trailing pathname component, leaving only the head.

So:

$ echo /ab/c/d
/ab/c/d
$ echo !$:h
echo /ab/c
/ab/c

The same shortcut can also be used with zsh.