Mac终端配置代理的脚本

点击下面链接 install_proxy.sh

GitHub仓库地址 YBScripts

鼠标右键另存为install_proxy.sh,对下载下来的文件执行加权命令:

chmod 777 install_proxy.sh

然后直接执行脚本:

./install_proxy.sh

Mac终端快速开启代理脚本使用说明

打开Mac 上的代理软件,并打开代理开关;

执行脚本,根据提示输入,提示 please input shortcut command of start proxy:时,输入在终端开启代理的命令,如果直接回车,默认为startproxy

提示please input shortcut command of end proxy:时,输入在终端关闭代理的命令,如果直接回车,默认为endproxy

提示please input proxy port:时,输入你的翻墙软件开启的代理端口,如ClashX默认端口为7890,如果直接回车,默认端口为7890

关闭终端窗口重新打开,或者执行source ~/.zshrc 或者 source ~/.bashrc 来立即应用环境变量;脚本运行完以后可删除此脚本;

脚本会在 zsh 的配置文件 ~/.zshrc 和 bash 的配置文件 ~/.bashrc 中生成 alias 命令,脚本执行完以后,在代理软件打开的情况下,可使用配置的 startproxy 命令和 endproxy 命令来快速开启和关闭终端代理;

执行 startproxy 输出结果如下:

可通过以下语句打印当前的代理:

echo -e "\n $http_proxy \n $https_proxy \n $all_proxy"

脚本内容预览:

#!/bin/bash
# author wangyingbo
# date:2023-03-07 pm 16:30

port='' # 端口号
startProxy='' # 开启代理的快捷命令
endProxy='' # 结束代理的快捷命令
pathzsh=~/.zshrc
pathbash=~/.bashrc
TIME=$(date "+%Y-%m-%d %H:%M:%S")
_DIR_=`pwd`
# pathzsh=$_DIR_/zshrc.txt
# pathbash=$_DIR_/bashrc.txt

green(){
	echo -e "\033[32;40m $1 \033[0m"
}
red(){
	echo -e "\033[31;40m $1 \033[0m"
}
yellow(){
	echo -e "\033[33;40m $1 \033[0m"
}

read -p "please input shortcut command of start proxy:" startProxy
if [[ -z $startProxy ]]; then
	yellow "default start proxy command is 'startproxy'"
	startProxy='startproxy'
else
	green "start proxy command is '$startProxy'"
fi

read -p "please input shortcut command of end proxy:" endProxy
if [[ -z $endProxy ]]; then
	yellow "default end proxy command is 'endproxy'"
	endProxy='endproxy'
else
	green "end proxy command is '$endProxy'"
fi

read -p "please input proxy port:" port
if [[ -z $port ]]; then
	yellow "default proxy port is 7890"
	port='7890'
else
	green "proxy port is '$port'"
fi

sleep 0.25

genproxy(){
	echo -e "\n" >> $1
	PROXYURL=http://127.0.0.1
	PROXYPORT=$port
	cat >> $1 <<PROXYEOF
# 设置代理
alias $startProxy="export http_proxy=$PROXYURL:$PROXYPORT https_proxy=$PROXYURL:$PROXYPORT;curl cip.cc"
# 取消代理
alias $endProxy="unset http_proxy https_proxy;curl cip.cc"
PROXYEOF
}

bashExist=$(grep $startProxy $pathbash)
zshExist=$(grep $startProxy $pathzsh)
if [[ -z $zshExist ]]; then
	echo ""
else
	red "\n"
	red "zsh alias proxy command has existed!"
	exit 1
fi
if [[ -z $bashExist ]]; then
	echo ""
else
	red "\n"
	red "bash alias proxy command has existed!"
	exit 0
fi

shellsource=''
if [ -n "`$SHELL -c 'echo $BASH_VERSION'`" ]; then
   # assume Bash
   shellsource='sh'
elif [ -n "`$SHELL -c 'echo $ZSH_VERSION'`" ]; then
   # assume Zsh
   shellsource='zsh'
else
   # something else like fish
   echo ""
fi

if [[ -e $pathzsh ]]; then
	genproxy $pathbash
	$shellsource $pathbash
	green "write proxy command to ${pathzsh##*/} successfully!"
fi

if [[ -e $pathbash ]]; then
	genproxy $pathzsh
	$shellsource $pathzsh
	green "write proxy command to ${pathbash##*/} successfully!"
fi

# shell excute time
echo ""
green "${TIME} ($0): this shell script execution duration: ${SECONDS}s"
echo ""