3

I have a simple shell script. What i'd like to do, is copy the files in /home/imp/imp/msgs/ to /home/imp/imp/msgs/bak/, but only if they are newer in the source directory than the destination directory.

#!/bin/bash
cp /home/imp/imp/msgs/*.MIX /home/imp/imp/msgs/bak/
cp /home/imp/imp/msgs/*.BRD /home/imp/imp/msgs/bak/

I tried cp -u, but it doesn't seem to work for me.

1

3 Answers 3

4

You can use rsync with the pattern *.MIX and *.BRD, e.g

rsync -avm --include='*.MIX' --include='*.BRD' --exclude='*' /home/imp/imp/msgs/ /home/imp/imp/msgs/bak/
3

You need to use cp -p to retain timestamps. Otherwise you can't​ usefully compare them next time.

cp -pu /home/imp/imp/msgs/*.MIX /home/imp/imp/msgs/bak/
cp -pu /home/imp/imp/msgs/*.BRD /home/imp/imp/msgs/bak/
1

Make

Here we generate Makefile dynamically using a heredoc and run the dynamic Makefile to accomplish the copy

cat - <<\CODE | make -f - SRCDIR="/home/imp/imp/msgs" XN="BRD MIX"
.PHONY: all
all: $(foreach i,$(foreach j,$(XN),$(wildcard $(SRCDIR)/*.$j)),$(addprefix $(join $(dir $i),bak/),$(notdir $i)))
cprule = $(SRCDIR)/bak/%.$1: $(SRCDIR)/%.$1; /bin/cp -p "$$^" "$$@"
$(foreach i,$(XN),$(eval $(call cprule,$i)))
CODE

Bash

SRCDIR="/home/imp/imp/msgs"
for src in "$SRCDIR"/*.MIX "$SRCDIR"/*.BRD
do
   dest=${src%/*}/bak/${src##*/}
   if [ ! -e "$dest" ] || [ "$src" -nt "$dest" ]
   then
      /bin/cp -p "$src" "$dest"
   fi
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .