Skip to content

Instantly share code, notes, and snippets.

@patinthehat
Created July 8, 2017 19:15
Show Gist options
  • Select an option

  • Save patinthehat/c0b40ad6e26cbd82ad72444c5275221c to your computer and use it in GitHub Desktop.

Select an option

Save patinthehat/c0b40ad6e26cbd82ad72444c5275221c to your computer and use it in GitHub Desktop.
Edit any nginx config file and then restart the service.
#!/bin/bash
SCRIPTNAME=$(basename $0)
NGINX_CONFIG_PATH="/etc/nginx"
DEFAULT_EDITOR=$(which nano)
FALLBACK_EDITOR=$(which vim)
[ "$EDITOR" == "" ] && EDITOR="$DEFAULT_EDITOR"
#No filename specified or (-h|--help) flag was passed.
if [ $# -eq 0 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo "Usage: ${SCRIPTNAME} <relative filename>"
echo "The path should be relative to ${NGINX_CONFIG_PATH}. i.e.:"
echo " ${SCRIPTNAME} nginx.conf"
echo " ${SCRIPTNAME} sites-enabled/default"
echo ""
exit 0
fi
TARGET_FILE="${NGINX_CONFIG_PATH}/$1"
#Ensure that the specified file actually exists, exit if it's not found.
if [ ! -f "$TARGET_FILE" ]; then
echo "Error: file not found: $TARGET_FILE"
exit 1
fi
#ensure the editor binary exists
if [ ! -x "$EDITOR" ]; then
echo "Error: Editor was either not specified (use env variable '\$EDITOR'), "
echo "was not found, or the default editor was not found."
echo "Using fallback editor ${FALLBACK_EDITOR}"
EDITOR="$FALLBACK_EDITOR"
if [ "$EDITOR" == "" ] || [ ! -x "$EDITOR" ]; then
echo "Error: a valid editor program could not be found. Please install nano or vim."
exit 1
fi
fi
#check to see if the file was modified after the editor exits.
TARGET_LAST_MOD_1=$(stat -L --printf="%Y" "$TARGET_FILE")
sudo $EDITOR "$TARGET_FILE"
TARGET_LAST_MOD_2=$(stat -L --printf="%Y" "$TARGET_FILE")
#Nothing changed, so no restart required
if [ "$TARGET_LAST_MOD_1" == "$TARGET_LAST_MOD_2" ]; then
echo -e "\e[0;33mFile was not modified, service restart not necessary.\e[0m"
exit 0
fi
echo -e "\e[0;33mFile WAS modified, testing configuration...\e[0m"
#test the nginx configuration
sudo nginx -t
if [ $? -eq 0 ]; then
echo -e "\e[0;32mnginx configuration test succeeded, restarting nginx service...\e[0m"
sudo service nginx restart
echo -e "\e[0;32mdone.\e[0m"
else
echo -e "\e[0;33mnginx configuration test failed, not restarting service.\e[0m"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment