Skip to content

Instantly share code, notes, and snippets.

@fortable1999
Created October 13, 2018 10:52
Show Gist options
  • Save fortable1999/7a9d20e9e8bce14aacc3d6c5f433462e to your computer and use it in GitHub Desktop.
Save fortable1999/7a9d20e9e8bce14aacc3d6c5f433462e to your computer and use it in GitHub Desktop.
copyfile.sh
#!/bin/bash
##
# format
# <TAG>,<SRC_PATH>,<DST_PATH>,<FLAGS>
#
##
## const defination
PARAM_FILE="/Users/zhao/Workspace/playground/param"
TAG=$1
IGNORE_FLAG="I"
## function defination ##
check_param_file () {
# check tags are uniq
if [ `awk -F',' '{print $1}' $PARAM_FILE | uniq | wc -l` -ne `awk -F',' '{print $1}' $PARAM_FILE | wc -l` ]
then
echo "tags are not uniq."
exit 1
fi
}
check_file_copyable () {
# check single file copyable
# test ok
src="$1"
dst="$2"
flg="$3"
if [[ "$flg" == "$IGNORE_FLAG" ]]
then
if [[ ! -f $dst ]]
then
echo 0
else
echo 1
fi
else
if [[ -f $src ]] && [[ ! -f $dst ]]
then
echo 0
else
echo 1
fi
fi
}
check_copyable () {
# check path copyable
src="$1"
dst="$2"
flg="$3"
if [[ -d "$src" ]]
then
# if src is a directory, check every file found in it
for path in `find "$src"`
do
if [[ -d $path ]]
then
# skip for directories
continue
fi
# check single file copyable
src_file=$path
relative_path=${path#"$src"}
dst_file=$dst$relative_path
if [[ `check_file_copyable "$src_file" "$dst_file" "$flg"` -ne 0 ]]
then
echo "$src_file does not exist or $dst_file already exist"
exit 1
fi
done
else
# check single file copyable
if [[ `check_file_copyable "$src" "$dst" "$flg"` -ne 0 ]]
then
echo "$src does not exist or $dst already exist"
exit 1
fi
fi
}
copy_file () {
# Copy file or directory.
# raise error code 1 when copy failed.
src="$1"
dst="$2"
flg="$3"
if [[ $flg == $IGNORE_FLAG ]]
then
# ignore error message.
cp -r $src $dst 2>/dev/null
else
cp -r $src $dst
if [ $? -ne 0 ]
then
echo "copy failed, $#"
exit 1
else
echo "copy ok"
fi
fi
}
## Main ##
check_param_file
IFS=$'\n'
for line in $(cat $PARAM_FILE)
do
opt="$(cut -d',' -f1 <<<"$line")"
src="$(cut -d',' -f2 <<<"$line")"
dst="$(cut -d',' -f3 <<<"$line")"
flg="$(cut -d',' -f4 <<<"$line")"
if [[ $TAG == $opt ]]; then
check_copyable "$src" "$dst" "$flg"
copy_file "$src" "$dst" "$flg"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment