Skip to content

Instantly share code, notes, and snippets.

@ramzes13
Last active February 26, 2019 07:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramzes13/c61d15a850e0f7bf2693 to your computer and use it in GitHub Desktop.
Save ramzes13/c61d15a850e0f7bf2693 to your computer and use it in GitHub Desktop.
#!/bin/bash
TMP_FILE='/tmp/media_hosts'
HOSTS_FILE='/etc/hosts'
DIVERTISMENT_START="=========================DIVERTISMENT_START====================="
DIVERTISMENT_END="=========================DIVERTISMENT_END======================="
D_START_FOUND=false;
D_END_FOUND=false;
> $TMP_FILE
writeLine() {
echo "$1" >> $TMP_FILE
}
insertMedia() {
writeLine "127.0.0.1 www.unimedia.info unimedia.info"
writeLine "127.0.0.1 www.protv.md protv.md"
writeLine "127.0.0.1 www.facebook.com facebook.com"
writeLine "127.0.0.1 www.point.md point.md"
}
if [[ $UID != 0 ]]; then
echo "Please run this script with sudo:"
echo "sudo $0 $*"
exit 1
fi
# begin
IFS=''
while read line
do
# check for start delimitator
if [[ "$D_START_FOUND" = false ]]
then
echo $line | grep -q $DIVERTISMENT_START
if [ $? -eq 0 ]
then
D_START_FOUND=true
# keep start delimitator line
writeLine $DIVERTISMENT_START
insertMedia
continue
fi
fi
# check for end delimitator
if [[ "$D_START_FOUND" = true ]]
then
echo $line | grep -q $DIVERTISMENT_END
if [ $? -eq 0 ]
then
D_END_FOUND=true
# keep end delimitator line
writeLine $DIVERTISMENT_END
continue
fi
fi
# before delimitators
if [[ "$D_START_FOUND" = false && "$D_END_FOUND" = false ]]
then
writeLine $line
fi
# after delimitators
if [[ "$D_START_FOUND" = true && "$D_END_FOUND" = true ]]
then
writeLine $line
fi
done < $HOSTS_FILE
# if delimitators not exist in file, create them
if [[ "$D_START_FOUND" = false && "$D_END_FOUND" = false ]]
then
writeLine $DIVERTISMENT_START
insertMedia
writeLine $DIVERTISMENT_END
fi
cat $TMP_FILE > $HOSTS_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment