Last active
June 28, 2018 04:18
-
-
Save santrancisco/391fe124730136ad5a854ed862701a1e to your computer and use it in GitHub Desktop.
Simple script to sync local copy of the code to remote server - helpful while debugging app remotely for example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
export DELETEONSYNC=true | |
export LOCALPATH=`perl -e 'use Cwd "abs_path";print abs_path(shift)' $1` | |
export REMOTEPATH=$3 | |
export LOCALPATHLENGTH=${#LOCALPATH} | |
export REMOTESERVER=$2 | |
export LISTEXT="$4" | |
function contains() { | |
local n=$# | |
local value=${!n} | |
for ((i=1;i < $#;i++)) { | |
if [ "${!i}" == "${value}" ]; then | |
echo "y" | |
return 0 | |
fi | |
} | |
echo "n" | |
return 1 | |
} | |
function syncfile() { | |
echo "Sync file function is triggered" | |
FILE=$1 | |
REMOTEFILE=$REMOTEPATH${FILE:$LOCALPATHLENGTH} | |
EXTENSION="${FILE#*.}" | |
IFS=', ' read -r -a FAVEXTENSIONS <<< "$LISTEXT" | |
if [ $(contains "${FAVEXTENSIONS[@],,}" "${EXTENSION,,}" ) == "y" ] # ${VAR_NAME,,} <-- make string VAR_NAME into lowercase. | |
then | |
echo "File $FILE is in the list of extenions we are syncing." | |
# If file does not exist (eg we deleted it, remove it on remote server) | |
if [ ! -f $FILE ]; then | |
if [[ "$DELETEONSYNC" = true ]]; then | |
echo "DELETING $REMOTEFILE on server" | |
ssh $REMOTESERVER "sudo rm $REMOTEFILE" | |
fi | |
return | |
fi | |
echo "Copying $FILE to remote server" | |
rsync -o -g --rsync-path="sudo rsync" $FILE $REMOTESERVER:$REMOTEFILE | |
## Comment this out if you dont want to change file owner to www:data. | |
ssh $REMOTESERVER "sudo chown www-data:www-data $REMOTEFILE" | |
echo synching $REMOTEFILE | |
fi | |
} | |
export -f syncfile | |
export -f contains | |
if [ ! $# -eq 4 ]; then | |
echo "Usage " | |
echo './fswatch.sh /LOCAL/PATH USERNAME@REMOTESERVER /REMOTE/PATH "LIST,OF,EXTENSION,WE,WANT,TO,SYNC" ' | |
echo 'eg: ./fswatch.sh ./app vagrant@192.168.33.213 /var/www/app "py,html,js" ' | |
echo -e "You should have ~/.ssh/ssh_config configured to either reuse existing ssh connection \nOR using private key to avoid password prompts as this script use alot of rsync and ssh to do its dirty work." | |
echo "Remote user should have sudo access that require no password. If you dont have this, modify the script to suit your need 🤷♂️" | |
exit | |
fi | |
echo "Starting fswatch on $LOCALPATH" | |
fswatch $LOCALPATH | xargs -I {} bash -c 'syncfile $@' _ {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment