Ubuntu – How to move found files to another directory

bashcommand linemv

Hello to everyone I have the following script that works fine except the mv argument. The script basically searching for the files that were created at a specific time and the I need to move all of the founded files to another directory with the name timefile

Script:

#!/bin/bash
read -rp 'hour ([0]0-23): ' hour
case $hour in
  (0|00)
    find /home/mikepnrs -newermt "yesterday 23:59" \
      ! -newermt 0:59 ;;
  (0[1-9]|1[0-9]|2[0-3])
    find /home/mikepnrs -newermt "$((10#$hour-1)):59" \
      ! -newermt "$hour:59" | mv -t /home/mikepnrs/timefile ;;
  (*)
    printf 'invalid hour: %s\n' "$hour"
esac

The syntax mv -t /home/mikepnrs/timefile seems not to be working. Error that I get is mv missing the file operand.

Any solutions?

Best Answer

Your pipe (find ... | mv ...) means sending STDOUT of find to STDIN of mv. But mv does not accept files from STDIN, only arguments.

You could translate STDIN to arguments using xargs:

find ... -print0 | xargs -0 mv -t target

(-print0 and xargs -0 to pipe null-delimited instead of newline-delimited output, because newline is a valid character as part of filenames).

But preferred option is to simply use find -exec:

find ... -exec mv -t target {} +

In your case:

find /home/mikepnrs -newermt "$((10#$hour-1)):59" \
  ! -newermt "$hour:59" -exec mv -t /home/mikepnrs/timefile {} +

Disclaimer: I did not check the rest of your script.

Related Question