Search code examples
permissionscronzshrsyncmv

Move file, change permissions and rename it keeping the same extesion


Using zsh 5.2 on Fedora 24 workstation.

I want to be programatically able to:

  • move an image file (can have jpg/ jpeg/ png/ JPG/ PNG extensions) from /tmp/folder1 to ~/Pictures
  • This file will have the same few initial characters --- prefix111.jpg OR prefix222.png, etc.
  • rename the file such that samefilename.JPG becomes 20161013.jpg
  • 20161013 is today's date in yyyymmdd format
  • Note that the extension becomes small letters
  • And JPEG or jpeg becomes jpg
  • change the permissions of the moved file to 644

All at one go.

If there are multiple prefix* files, the command should just fail silently.

I will initially like to do it at the command prompt with an option to add a cron job later. I mean, will the same zsh command/ script work in cron?

I am sure, this is doable. However, with my limited shell knowledge, could only achieve:

mv /tmp/folder1/prefix-*.JPG ~/Pictures/$(date +'%Y%m%d').jpg

Problems with my approach are many. It does not handle capitalization, does not take care of different extensions and does not address the permission issue.


Solution

  • How about this:

    #!/bin/sh
    FILES="/tmp/folder1/prefix*.jpg /tmp/folder1/prefix*.jpeg /tmp/folder1/prefix*.png h/tmp/folder1/prefix*.JPG /tmp/folder1/prefix*.PNG"
    if [ $(ls $FILES | wc -l ) -gt 1 ]; then
        exit 1
    fi
    if [ $(ls $FILES | grep -i '\.png$') ]; then
      SUFF=png
    else
      SUFF=jpg
    fi
    DEST=$HOME/Pictures/$(date +'%Y%m%d').$SUFF
    mv $FILES $DEST
    chmod 644 $DEST