本人的Ubuntu20.04 环境switchhosts 切换不了,可能是程序bug,又着急用,于是写了个脚本
# 安装到 ~/bin 下
mkdir -p ~/bin/hostlist
echo "export PATH=$PATH:$HOME/bin" >> ~/.bash_profile
source ~/.bash_profile
touch ~/bin/chhost
chmod +x ~/bin/chhost
# 备份系统hosts
cat /etc/hosts > ~/bin/hostlist/system.hosts.txt
vim ~/bin/chhost
#!/usr/bin/bash
#
function changeHost()
{
scriptDir=$(cd $(dirname $0); pwd)
echo "Switch to $1 hosts ..."
pathhost=$scriptDir"/hostlist"
file=$pathhost"/"$1".hosts.txt"
if [ ! -f "$file" ]; then
echo "file not exits!: $file "
echo ""
echo "Include this hosts:"
hosts=`/usr/bin/ls $pathhost | /usr/bin/sed 's/.hosts.txt//g' | /usr/bin/sed 's/tmp//g'`
echo $hosts
ls $pathhost
echo ""
exit
fi
systemfile=$pathhost"/system.hosts.txt"
tmpfile=$pathhost"tmp.hosts.txt"
/usr/bin/cp $systemfile $tmpfile
/usr/bin/cat $file >> $tmpfile
/usr/bin/sudo /usr/bin/cp $tmpfile /etc/hosts
echo "Switch to $1 hosts success!"
}
changeHost $1
在 ~/bin/hostlist 目录下创建 一系列 xxx.hosts.txt 命名的文件
就可以切换到 xxx.hosts.txt 的环境
xxx.hosts.txt 文件格式与 /etc/hosts 文件格式相同
使用例子my 编辑my.hosts.txt :
~/bin/hostslist/my.hosts.txt
# start my hosts
199.232.68.133 raw.githubusercontent.com
151.101.76.133 raw.githubusercontent.com
# end my hosts
chhost my