Will this work?

I'm trying to check if files already exist in a directory. They have the same basename (exsyctr1), but 4 different extensions. If the files exist, then I make backups of them, then copy them from another directory ($livecomp/data) to the current one ($copycomp/data). If they don't exist, just perform the copy.

Will the script below work?

  if [ -f $copycomp/data/exsyctr1.* ]
  then
	echo "Changing to $copycomp/data/"
	cd $copycomp/data
	echo "Backing up existing files"
	cp exsyctl1.* *.bak
	echo "Copying from $livecomp/data/ to $copycomp/data/"
	cp $livecomp/data/exsyctr1.* .
  else
	echo "Copying from $livecomp/data/ to $copycomp/data/"
	cp $livecomp/data/exsyctr1.* .
  fi

I would use a loop like the following, but it's just one possible way I suppose...

echo "Changing to $copycomp/data/"
cd $copycomp/data

for FILE in `ls $copycomp/data/exsyctr1.*`
do
  if [ -f $FILE ]; then
    echo "Backing up existing files"
    cp $FILE ${FILE%.*}.bak
  fi
done

echo "Copying from $livecomp/data/ to $copycomp/data/"
cp $livecomp/data/exsyctr1.* .

If you're not using KSH, then replace "cp $FILE ${FILE%.}.bak" with "cp $FILE `echo $FILE | sed 's/\([^.]*\)./\1/'`.bak"

If you're serious about finding out different ways to do things, read this post. Maybe you'll like one way more than another.

Only the first file is renamed, Oombera... :frowning:

ignore that, fixed it :slight_smile:

thanks oombera

In oombera's solution, the "if" is redundant, since `ls ...` only returned the files that were there, not the ones that weren't.

Assuming the "extensions", i.e., the filename endings after a period, are fixed, my solution would be something like this:

cd $copycomp/data
for ext in a b c d ; do
    if [ -f exsyctr1.$ext ] ; then
        # Create backup file per oombera, notice shell differences.
	cp $livecomp/exsyctrl.$ext .
    fi
done

Well, it might not be redundant if the particular $copycomp/data/exsyctr1.* the loop is currently testing happens to be a directory instead of a regular file. :wink: