:note

cp -p で更新日を維持してコピー

cpコマンドでファイルをコピーすると、更新日が今になってしまうので、 そういう処理が必要な時に、AppleScriptをつかったりしていたけど

cp -p

でいいらしい

% ls -l ~/Downloads/image.jpg
-rw-r--r--@ 1 xxxxx  staff  125231  3  3 09:23 /Users/xxxxx/Downloads/image.jpg
           
# 日付が変わる
% cp ~/Downloads/image.jpg ~/Desktop/no_p
% ls -l ~/Desktop/no_p
total 248
-rw-r--r--@  1 xxxxx  staff  125231  3  7 12:09 image.jpg

# 日付が変わらない
% cp -p ~/Downloads/image.jpg ~/Desktop/with_p
% ls -l ~/Desktop/with_p
total 248
-rw-r--r--@  1 xxxxx  staff  125231  3  3 09:23 image.jpg

macOS

% man cp

     -p    Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode,
           user ID, and group ID, as allowed by permissions.  Access Control Lists (ACLs) and Extended Attributes (EAs), including resource forks,
           will also be preserved.

           If the user ID and group ID cannot be preserved, no error message is displayed and the exit value is not altered.

           If the source file has its set-user-ID bit on and the user ID cannot be preserved, the set-user-ID bit is not preserved in the copy's
           permissions.  If the source file has its set-group-ID bit on and the group ID cannot be preserved, the set-group-ID bit is not pre-
           served in the copy's permissions.  If the source file has both its set-user-ID and set-group-ID bits on, and either the user ID or
           group ID cannot be preserved, neither the set-user-ID nor set-group-ID bits are preserved in the copy's permissions.

ubuntu

$ man cp

       -p     same as --preserve=mode,ownership,timestamps

       --preserve[=ATTR_LIST]
              preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all

rubyの FileUtils#cp でやる場合

require 'fileutils'
include FileUtils

src_path   = "/Users/xxxxx/Downloads/image.jpg"
dir_path   = "/Users/xxxxx/Desktop/no_p"
dir_path_p = "/Users/xxxxx/Desktop/with_p"

cp src_path, dir_path

cp src_path, dir_path_p, preserve: true

ファイルに拡張子が付いていたらどちらも同じ挙動をした。

ただし、 拡張子がないファイル!は、 FileUtilsのcpだと、プレビューアイコンもなくなり、 unix実行ファイルになってしまう。

cp -p で更新日を維持してコピー /images/2017-03-09-file-stat-size.png

どうしても、rubyでやるときには system "cp -p xx yy" みたいになる必要がある。

 
comments powered by Disqus
back to top