Created
January 31, 2018 06:11
-
-
Save int128/e7f9a394c62ed06bccd4476f12ef6d9d to your computer and use it in GitHub Desktop.
Shell script to switch symbolic link
This file contains hidden or 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 -e | |
# Directory that contains sources | |
SOURCE_DIR="/example/source" | |
# Directory to deploy sources to | |
TARGET_DIR="/example/bin" | |
# Directory to keep old generations | |
STAGING_DIR="/example/staging" | |
# Directory of the latest generation | |
LATEST_DIR="${STAGING_DIR}/$(date +%Y%m%d.%H%M%S)" | |
# Log file | |
LOG_FILE="/example/log/deploy.log" | |
function append_log () { | |
if [ -d "$(dirname "$LOG_FILE")" ]; then | |
tee -a "$LOG_FILE" | |
else | |
tee | |
fi | |
} | |
function log_info () { | |
echo "$(date --iso-8601=seconds) [deploy] $*" | append_log | |
} | |
function log_exec () { | |
log_info "$@" | |
"$@" 2>&1 | append_log | |
if [ "${PIPESTATUS[0]}" -ne 0 ]; then | |
false | |
fi | |
} | |
log_info "Deploying..." | |
log_info "Copying sources into $LATEST_DIR" | |
log_exec mkdir -vp "$LATEST_DIR" | |
log_exec cp -vaT "$SOURCE_DIR" "$LATEST_DIR" | |
log_info "Updating symbolic link: $TARGET_DIR -> $LATEST_DIR" | |
log_exec ln -vs "$LATEST_DIR" "${TARGET_DIR}_tmp" | |
log_exec mv -vT "${TARGET_DIR}_tmp" "$TARGET_DIR" | |
log_info "Removing old generations..." | |
ls -t "$STAGING_DIR" | tail -n +5 | while read item; do | |
log_exec rm -fr "$STAGING_DIR/$item" | |
done | |
log_info "Successfully deployed" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment