mac&linux.sh 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/bin/bash
  2. # Copyright (c)2022 http://maruifu.cn
  3. # This is a batch script for fixing Google Translate and making it available
  4. # in the Chinese mainland. If you experience any problem, visit the page below:
  5. # http://maruifu.cn/article/251
  6. SOURCE_DOMAIN=google.cn
  7. TARGET_DOMAIN=translate.googleapis.com
  8. HOSTS_FILE=/etc/hosts
  9. HOST_CMD=/usr/bin/host
  10. CUT_CMD=/usr/bin/cut
  11. SED_CMD=/usr/bin/sed
  12. IP=$($HOST_CMD -t A $SOURCE_DOMAIN | $CUT_CMD -d ' ' -f 4)
  13. OLD_RULE=$(cat $HOSTS_FILE | grep $TARGET_DOMAIN)
  14. NEW_RULE="$IP $TARGET_DOMAIN"
  15. COMMENT="# Fix Google Translate CN"
  16. if [ -n "$OLD_RULE" ]; then
  17. echo "A rule has been added to the hosts file. "
  18. echo "[1] Update [2] Delete"
  19. echo -n "Enter a number to choose an action: "
  20. read action
  21. if [ "$action" == "1" ]; then
  22. if [ "$OLD_RULE" != "$NEW_RULE" ]; then
  23. echo "Deleting the rule \"$OLD_RULE\""
  24. echo "Adding the rule \"$NEW_RULE\""
  25. $SED_CMD -i '' "s/.*${TARGET_DOMAIN}/${NEW_RULE}/" $HOSTS_FILE
  26. else
  27. echo 'The rule already exists, nothing to do.'
  28. fi
  29. fi
  30. if [ "$action" == "2" ]; then
  31. echo "Deleting the rule \"$OLD_RULE\""
  32. PATTERN="s/\n\{0,\}${COMMENT}\n.* ${TARGET_DOMAIN}//"
  33. $SED_CMD -i '' -e ':a' -e 'N' -e '$!ba' -e "$PATTERN" $HOSTS_FILE
  34. fi
  35. else
  36. echo "Adding the rule \"$NEW_RULE\""
  37. echo -ne "\n${COMMENT}\n${NEW_RULE}" >> $HOSTS_FILE
  38. fi
  39. echo 'Done.'