在 Ubuntu 上编写通用脚本管理 Clash 全局代理

在 Linux 下使用 Clash 代理时,我们通常需要手动启动 Clash 程序,并设置 http_proxyhttps_proxy 等环境变量来实现全局代理。如果频繁切换代理,这样做会非常麻烦。

本文将演示如何编写一个通用脚本,一键启动或关闭 Clash,并实现全局代理切换。


1. Clash 启动命令回顾

假设 Clash 的配置文件路径为:

1
~/.config/clash/config.yaml

手动启动方式为:

1
clash -f ~/.config/clash/config.yaml

默认 REST API 监听在 9090 端口,代理监听在 7890 端口。


2. 编写代理控制脚本

新建一个脚本文件 proxy.sh

1
nano proxy.sh

写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash

CLASH_CONFIG="$HOME/.config/clash/config.yaml"
CLASH_BIN="$(which clash)"
CLASH_LOG="$HOME/.config/clash/clash.log"
CLASH_PID="$HOME/.config/clash/clash.pid"

start_proxy() {
echo "启动 Clash 并开启全局代理..."

# 如果已有 Clash 进程,先杀掉
if [ -f "$CLASH_PID" ] && kill -0 $(cat "$CLASH_PID") 2>/dev/null; then
echo "Clash 已在运行,先停止..."
stop_proxy
fi

nohup "$CLASH_BIN" -f "$CLASH_CONFIG" > "$CLASH_LOG" 2>&1 &
echo $! > "$CLASH_PID"

export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"
export all_proxy="socks5://127.0.0.1:7890"

echo "代理已开启,日志文件: $CLASH_LOG"
}

stop_proxy() {
echo "停止 Clash 并关闭全局代理..."

if [ -f "$CLASH_PID" ]; then
kill $(cat "$CLASH_PID") 2>/dev/null
rm -f "$CLASH_PID"
echo "Clash 已停止"
else
echo "Clash 未运行"
fi

unset http_proxy
unset https_proxy
unset all_proxy

echo "代理已关闭"
}

case "$1" in
start)
start_proxy
;;
stop)
stop_proxy
;;
restart)
stop_proxy
start_proxy
;;
*)
echo "用法: $0 {start|stop|restart}"
exit 1
;;
esac

保存后给脚本执行权限:

1
chmod +x proxy.sh

3. 全局使用脚本

为了在任意目录下都能使用该脚本,我们将其移动到 /usr/local/bin

1
sudo mv proxy.sh /usr/local/bin/proxy

此时我们就可以在任何位置直接使用:

1
2
3
proxy start    # 启动 Clash 并开启全局代理
proxy stop # 停止 Clash 并关闭全局代理
proxy restart # 重启 Clash

4. 日志与调试

  • Clash 的运行日志会保存在 ~/.config/clash/clash.log
  • 进程 PID 文件保存在 ~/.config/clash/clash.pid

如果 Clash 无法启动或代理失效,可以直接查看日志:

1
tail -f ~/.config/clash/clash.log

5. 总结

通过以上方法,我们实现了:

  • 一键开启/关闭代理
  • 全局环境变量设置
  • 脚本全局可用(所有路径都能调用)

这样在日常开发和远程连接时,就可以方便地切换 Clash 代理环境。

该封面图片由the_iopPixabay上发布