-1

This question is a variant on a previously asked How to repeat currently typed in parameter on bash console?


Many a time, I find myself wanting to slightly rename a file name in the shell, e.g.:

$ mv test_1.py _test_1.py

or

$ mv test_1.py test_1.py.org

I could use the suggestions in How to repeat currently typed in parameter on bash console?, but

is there any bash magic that will allow me to just reference the previously typed parameter?

e.g., if the magic is $M, then - for the above - I'd use:

$ mv test_1.py _$M.py
$ mv test_1.py $M.org

1 Answers1

1

The magic works in two parts.

First, echo is aliased to e (echo will work also if you want no alias); second, we use "brace expansion":

$ e mv {,_}test_1.py              # Try to see if it works as expected.
mv test_1.py _test_1.py

          # If the arguments are what you want:

$ mv {,_}test_1.py                # Press ↑ (up arrow), remove `e`

$ !*                              # OR: Type `!*` --> last line after arg 0.
$ mv {,_}test_1.py                # If `histverify` is set.

The !* may be expanded with an space if you enable magic-space or if you set shopt -s histverify after you press enter, you will be given a chance to review the effect of the history expansion before pressing enter (again) to execute.

The other example:

$ e mv test_1.py{,.org}
mv test_1.py test_1.py.org        # The result of the brace expansion.
                                  # Review it, and if it is ok:
$ !*                              # type !* (use either space or enter)
                                  # That will depend on how you setup it.

$ mv test_1.py{,.org}        # The command appear again (enter to execute).
$

There is also the history expansion of !# which means the command line typed so far, and selecting the first command :1. If you have magic-space enabled, you type mv test1.py !#:1 and press space, the command will change:

$ mv test_1.py !#:1                # Press space.
$ mv test_1.py test_1.py           # The command line change to this.
$ mv test_1.py test_1.org          # Edit and press enter to execute.