From 7655bd6a60f5e0c0c0c8968b177e74536e1b380c Mon Sep 17 00:00:00 2001 From: leafee98 Date: Thu, 17 Nov 2022 16:38:21 +0800 Subject: [PATCH] =?UTF-8?q?modify=20post:=20=E4=B8=BA=E5=8D=95=E4=B8=80?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E8=AE=BE=E7=BD=AE=E7=8E=AF=E5=A2=83=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E7=9A=84=E7=BB=88=E7=AB=AF=E5=87=BD=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../为单一命令设置代理环境变量的终端函数.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/content/posts/为单一命令设置代理环境变量的终端函数.md b/content/posts/为单一命令设置代理环境变量的终端函数.md index c90546d..a2bea75 100644 --- a/content/posts/为单一命令设置代理环境变量的终端函数.md +++ b/content/posts/为单一命令设置代理环境变量的终端函数.md @@ -1,6 +1,7 @@ --- title: "为单一命令设置环境变量的终端函数" date: 2021-04-19T14:10:41+08:00 +lastmod: 2022-11-17T16:36:00+08:00 tags: [ linux, shell, bash ] categories: [ tech ] weight: 50 @@ -37,6 +38,20 @@ function proxyenv { } ``` +### 针对 sudo 命令 + +在使用 `sudo` 命令时,它的默认行为是不保留任何当前 shell 下的环境变量,因此即便使用 `proxyenv sudo wget` 命令,也无法在 `wget` 中使用这些环境变量。一个临时的解决方案是使用 `sudo` 的 `--preserve-env` 参数,像下面这样 + +``` +$ proxyenv sudo -E wget http://example.org +``` + +如果希望简化每次需要敲的命令,可以在 `/etc/sudoer` 中添加以下内容,如此便可以每次默认保留这几个环境变量,`proxyenv sudo wget` 也会保留这些环境变量。 + +``` +Defaults env_keep += "PROXY HTTP_PROXY HTTPS_PROXY proxy http_proxy https_proxy" +``` + ### 分析 使用圆括号创建 subshell 来隔离原来的变量环境, 在内部创建变量或 export 不会影响外部 shell 的变量. @@ -95,3 +110,4 @@ hello shell 1. [What is the best way to write a wrapper function that runs commands and logs their exit code](https://stackoverflow.com/questions/372116/what-is-the-best-way-to-write-a-wrapper-function-that-runs-commands-and-logs-the/372120#372120) 2. [Bash script - variable content as a command to run](https://stackoverflow.com/questions/5998066/bash-script-variable-content-as-a-command-to-run/39458935#39458935) 3. [Do parentheses really put the command in a subshell?](https://unix.stackexchange.com/questions/138463/do-parentheses-really-put-the-command-in-a-subshell/138498#138498) +4. [sudoer(5) - Linux manual page](https://man7.org/linux/man-pages/man5/sudoers.5.html)