I find myself frequently needing to rename different files with mv that are in deep directories:

mv /a/long/path/to/a/file.txt /a/long/path/to/a/file.txt.bak

But I don't want to retype the full path name. Is there a quick shorthand or alias that I could use? I.e.:

$ mv /a/long/path/to/a/file.txt file.txt.bak
$ ls /a/long/path/to/a/file.txt.bak

(note: this is for straightforward, single file renames in different directories at different times, not for mass-renames)

  • Relating unix.stackexchange.com/a/6036/117549 – Jeff Schaller May 12 '20 at 0:03
  • Hi ascendants and welcome to SE. In order to signal to others in the Community that your question received a satisfactory answer, do not forget to mark your favorite accepted answer with a green check mark. Cheers. – Cbhihe May 12 '20 at 6:19

Use a brace expansion:

mv /a/long/path/to/a/file.txt{,.bak}

This renames /a/long/path/to/a/file.txt with an empty suffix to /a/long/path/to/a/file.txt with suffix .bak.

  • Thank you! This is a nice way without aliasing. – ascendants May 11 '20 at 23:01

Although I'd probably use brace expansion, as illustrated in Freddy's answer, in both bash and zsh one could use interactive history expansion, with designator #$ to refer to the last word typed so far on the current line:

mv /a/long/path/to/a/file.txt !#$.bak

This may be a basic question, but I hadn't found a existing question/answer for this. The simple solution I made was a function in ~./bash_functions**:


function mv-rn() {
  mv $1 $(dirname $1)/${2}

So that now:

$ mv-rn /a/long/path/to/a/file.txt file.txt.bak
$ ls /a/long/path/to/a/file.txt.bak

(**note that you must have this in your ~/.bashrc for the above function to be recognized as an alias):

# Function definitions.
if [ -f ~/.bash_functions ]; then
    . ~/.bash_functions
(cd /a/long/path/to/a && mv file.txt file.txt.bak)

The && ensures that the mv will be executed only if the cd succeeds. The parentheses mean that the commands will execute in a subshell, so the cd will not change your existing shell's working directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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