modify post: 为单一命令设置环境变量的终端函数.md

This commit is contained in:
leafee98 2022-11-17 16:38:21 +08:00
parent caea3a4377
commit 7655bd6a60

View file

@ -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)