I am trying to write a script, that will copy file or directory with added timestamp to filename/dirname

Something like:

cover.jpg --> cover_18-01-2014_17:37:32.jpg
directory --> directory_18-01-2014_17:37:32

I don't know how to add the timestamp to filename/dirname. Can anybody help?


now="$(date +'%d-%m-%Y_%T')"

With a pax implementation whose regexps support the \| operator:

now=$(date +%F_%T)
pax -rw -"s@/\(\([^/]*\)\(\.[^/]*\)\|\([^/.]*\)\)@/\2\4_$now\3@g" . /dest/

I really recommend using the 2014-01-18 format instead as that's unambiguous and it sorts the same way lexicographically and chronologically.

If you don't have pax, but have GNU tar, you can write it instead:

tar -cf - --transform="s@/\(\([^/]*\)\(\.[^/]*\)\|\([^/.]*\)\)@/\2\4_$now\3@g" . |
  (cd /dest && tar xf -)

In both cases, if there are symlinks in there, the substitution also applies to the target of the symlink and is unlikely to be done appropriately unless all the link targets are of the form ./some/thing.


It would help if you added the script you are trying to debug, but here is what I would be doing. You must specify two arguments to the script including the paths trailing slash (it does not input validation to remain brief).

$ datestamp-cp.sh /path/to/source/ /path/to/destination/

Contents of datestamp-cp.sh

#/bin/env sh
NOW=$(date +'%d-%m-%Y_%T')

for F in `ls $SRC`; do
  EXT=`rev $F|cut -d. -f1`
  cp -r $SRC$F $DST$NAM-$NOW.$EXT

If you want each file to have the exact time it was moved (matching the timestamp), move the NOW= line inside the FOR loop.

Dont forget to make the script executable

chmod u+x datestamp-cp.sh
  • this is sudo-code and not tested

I managed to write script on my own afterwhile

now="$(date +'%d-%m-%Y_%T')"

filename=$(basename "$1") 

cp -r "$1"  "$2"

if [ -f "$1" ]; then
   mv -f "$2/$filename" "$2/${name}_${now}.$extension"
   mv -f "$2/$filename" "$2/${filename}_${now}"

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.