Created
May 9, 2015 19:05
-
-
Save jacksgt/56dd2dfc115fde19ccf0 to your computer and use it in GitHub Desktop.
Bash File Mirror Script via HTTP
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 | |
# A bash script for mirroring a file | |
# Exit codes: | |
# -1 = local file up to date, nothing to do | |
# 0 = updated local file, successfull | |
# 1 (and above) = failure | |
# Written by Jack Henschel for https://cubieserver.de/blog/ | |
REMOTE_FILE="https://kernel.org/index.html"; | |
LOCAL_FILE="mirror.html"; | |
V=1 # Verbosity: 0 for quiet, 1 for normal | |
# Check if the remote file is available | |
if [[ $( curl -s -o /dev/null -w "%{http_code}" "$REMOTE_FILE" ) != 200 ]]; then | |
if [ $V -gt 0 ]; then | |
echo "Error while checking for remote file $REMOTE_FILE"; | |
fi | |
exit 1; | |
fi | |
# Check the local file (existence and permissions) | |
if [[ -e "$LOCAL_FILE" ]] && [[ ! -w "$LOCAL_FILE" ]]; then | |
if [ $V -gt 0 ]; then | |
echo "Error: no write permisssions on local file $LOCAL_FILE"; | |
fi | |
exit 1; | |
fi | |
# Get date of remote file | |
REMOTE_DATE=$( date -d "$( curl -Is $REMOTE_FILE | grep 'Modified' | cut -d',' -f2 )" "+%s" ); | |
# Check if we actually got only a digit | |
if [[ ! "$REMOTE_DATE" =~ [[:digit:]] ]]; then | |
if [ $V -gt 0 ]; then | |
echo "Error while parsing remote date: $REMOTE_DATE"; | |
fi | |
exit 1; | |
fi | |
# Get date of local file | |
if [[ -e "$LOCAL_FILE" ]]; then | |
LOCAL_DATE=$( stat "$LOCAL_FILE" -c "%Y" ); | |
else | |
LOCAL_DATE=0; | |
touch "$LOCAL_FILE" >> /dev/null 2>&1; | |
if [ $? -eq 1 ]; then | |
if [ $V -gt 0 ]; then | |
echo "Error: could not create local file $LOCAL_FILE"; | |
fi | |
exit 1; | |
fi | |
fi | |
# Check if we actually got only a digit | |
if [[ ! "$LOCAL_DATE" =~ [[:digit:]] ]]; then | |
if [ $V -gt 0 ]; then | |
echo "Error while parsing local date: $LOCAL_DATE"; | |
fi | |
exit 1; | |
fi | |
# Check if local file is younger than remote file | |
if [ $LOCAL_DATE -gt $REMOTE_DATE ]; then | |
if [ $V -gt 0 ]; then | |
echo "File is up to date"; | |
fi | |
exit -1; | |
else | |
curl -s "$REMOTE_FILE" -o "$LOCAL_FILE"; | |
if [ $V -gt 0 ]; then | |
echo "File has been updated"; | |
fi | |
fi | |
exit 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment