TransWikia.com

mv: rename X to Y: No such file or directory

Super User Asked by roccobarbi on December 11, 2021

On mac os (with zsh), I often find myself having to copy the last downloaded file to the current directory.

Having already defined the function lastn as follows:

function lastn() {
  if [ $# -eq 0 ]
    then
        echo ""
        echo "Usage:"
        echo "lastn <path> [n]"
        echo ""
  fi
  if [ $# -eq 1 ]
    then
      ls -lht $argv[1] | head -10
    else
      ls -lht $argv[1] | head -$argv[2]
  fi
}

I have tried these scripts:

{echo "~/Downloads"; lastn ~/Downloads 2 | tail -1 | sed 's/.* //';} | tr "n" "/" | sed 's//$//' | xargs -I % mv % ./

ORIGIN=$({echo "~/Downloads"; lastn ~/Downloads 2 | tail -1 | sed 's/.* //';} | tr "n" "/" | sed 's//$//'); mv $ORIGIN ./

In both cases, I always get an error of the type:

mv: rename ~/Downloads/filename to ./filename: No such file or directory

On the other hand, if I simply copy the output of the first part of both scripts:

{echo "~/Downloads"; lastn ~/Downloads 2 | tail -1 | sed 's/.* //';} | tr "n" "/" | sed 's//$//'

and use it as-is by pasting it as the first argoment of mv, the command works as expected.

What am I doing wrong here?

One Answer

You don't need to use absolute paths. You just need to rewrite your function like this:

lastn() {
  # Reset all options to safe defaults for this function only.
  emulate -LR zsh -o noshortloops -o warncreateglobal -o extendedglob

  # Get files sorted by modification date (or failing that, an empty array).
  local -a files=( $1/*(Nom) )

  case $# in
    0)
      echo "Usage:"
      echo "lastn <path> [n]"
      return 1
      ;;
    1)
      reply=( $files[1] )
      ;;
    *)
      reply=( $files[1,$2] )
      ;;
  esac

  # This is not necessary, but gives the user something to look at.
  echo $reply

  # Report success only when we actually have something to return.
  (( $#reply > 0 ))
}

Then you can simply do the following:

lastn ~/Downloads 2 && mv $reply .

The last line of the function makes it so that, if we don't get any results, then the command following && won't get executed.

Answered by Marlon Richert on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP