替換檔案

在upgrade jar檔的時候,必然會先做測試,而這個jar檔可能會依照專案不同分散在不同的地方。如果要一個個替代實在非常麻煩,因此我撰寫了一個shellscript替我做這件事情,希望能夠幫助大家。這個script接受三個參數:

  1. 被替代的檔案
  2. 要替代的檔案
  3. 開始路徑: 預設為/目錄

Example:

>./replace_files.sh example-1.11.1.jar example2.1.0.jar /opt
Replace /opt/Example/libs/example-1.11.1.jar with example2.1.0.jar
Replace /opt/Example2/libs/example-1.11.1.jar with example2.1.0.jar
Total: 2 files.

#!/bin/bash
FULLPATH=`dirname "$0"`/`basename "$0"`
BASE=`readlink -f "$FULLPATH"`
BASEPATH=`dirname $BASE`

# check arguments
if [ "$4" != "" -o ! -d "$3" ]; then
	echo Please check the arguments.
	exit 1
fi

# setup searching path
SEARCH_BASE=$3
if [ "$SEARCH_BASE" == "" ]; then
	SEARCH_BASE=/
fi
if [ ! -e "$SEARCH_BASE" ]; then
	echo $SEARCH_BASE doesn\'t exist.
	exit 1
fi

# setup the target file path
REPLACED_FILE=$2
if [ ! -e "$TARGET_FILE" ]; then
	REPLACED_FILE=$BASEPATH/$2
fi
if [ ! -e "$REPLACED_FILE" ]; then
	echo $2 doesn\'t  exist.
fi

# find the target files
IFS=$'\n'
TARGET_FILE="$1"
filelist=(`find $SEARCH_BASE -name "$TARGET_FILE"`)

# replace the files
declare -i count=0
for filepath in ${filelist[@]}; do
	dirname=`dirname $filepath`
	if [ "$filepath" == "$REPLACED_FILE" -o "$filepath" == "$BASEPATH/$REPLACED_FILE" ]; then
		continue
	fi
	count=$count+1
	echo Replace "$filepath" with "$2"
	rm -rf $filepath
	cp -f $REPLACED_FILE $dirname
done

echo Total: $count files.

PS. 這個script的第一個參數是能夠接受*的,但如果在和jar檔同一個路徑執行… 會發生什麼問題我可不曉得…