How to Set Up a Network Proxy in Terminal Shell

Terminal Shell on OS does not use the system proxy, so even if the system proxy is enabled, commands like curl or npm in iTerm2 may still face network issues.

Proxy apps like Surge or others that support modifying the network card can force the terminal to use the proxy, but sometimes, we don’t want to use this method. So, Can the terminal shell use the proxy?

Yes, there is. Here is the solution.

https://static.1991421.cn/2024/2024-07-13-122755.jpeg

Shell Configuration File

Here, take bash as an example. Open the bash_profile by vi/.bash_profile. If you usually use zsh, you can also vi ~/.zshrc`.

Add the following configuration:

1
2
3
4
5
export http_proxy=socks5://127.0.0.1:6153
export https_proxy=$http_proxy
export all_proxy=$http_proxy

alias disproxy='unset http_proxy https_proxy all_proxy'

If you only want to solve the terminal HTTP request proxy, you can skip configuring all_proxy. Since requests are not always HTTP, you can configure all_proxy to solve HTTP requests.

Note that git ssh will not use this configuration. The solution is to configure proxyCommand for git separately or use the enhanced mode of the proxy software.

Apply Configuration

source ~/.bash_profile

Test

curl -i https://google.com

If the system proxy service itself has network request packet capture, you can judge whether the proxy is effective through packet capture.

Temporarily Disable Proxy

Because we have added disproxy in the configuration, execute disproxy.

At the end

This way, the requests sent by the terminal shell can use the proxy service.