如何在 Linux 上运行命令前临时清空 Bash 环境变量

转载说明:总结成一句,就是在执行命令之前加 env -i


我是个 bash shell 用户。我想临时清空 bash shell 环境变量。但我不想删除或者 unset 一个输出的环境变量。我怎样才能在 bash 或 ksh shell 的临时环境中运行程序呢?

你可以在 Linux 或类 Unix 系统中使用 env 命令设置并打印环境。env 命令可以按命令行指定的变量来修改环境,之后再执行程序。

如何显示当前环境?

打开终端应用程序并输入下面的其中一个命令:

  
  
  1. printenv

  
  
  1. env

输出样例:

Fig.01: Unix/Linux: 列出所有环境变量

Fig.01: Unix/Linux: 列出所有环境变量

统计环境变量数目

输入下面的命令:

  
  
  1. env | wc -l
  2. printenv | wc -l # 或者

输出样例:

  
  
  1. 20

在干净的 bash/ksh/zsh 环境中运行程序

语法如下所示:

  
  
  1. env -i your-program-name-here arg1 arg2 ...

例如,要在不使用 http_proxy 和/或任何其它环境变量的情况下运行 wget 程序。临时清除所有 bash/ksh/zsh 环境变量并运行 wget 程序:

  
  
  1. env -i /usr/local/bin/wget www.cyberciti.biz
  2. env -i wget www.cyberciti.biz # 或者

这当你想忽视任何已经设置的环境变量来运行命令时非常有用。我每天都会多次使用这个命令,以便忽视 http_proxy 和其它我设置的环境变量。

例子:使用 http_proxy
  
  
  1. $ wget www.cyberciti.biz
  2. --2015-08-03 23:20:23-- http://www.cyberciti.biz/
  3. Connecting to 10.12.249.194:3128... connected.
  4. Proxy request sent, awaiting response... 200 OK
  5. Length: unspecified [text/html]
  6. Saving to: 'index.html'
  7. index.html [ <=> ] 36.17K 87.0KB/s in 0.4s
  8. 2015-08-03 23:20:24 (87.0 KB/s) - 'index.html' saved [37041]
例子:忽视 http_proxy
  
  
  1. $ env -i /usr/local/bin/wget www.cyberciti.biz
  2. --2015-08-03 23:25:17-- http://www.cyberciti.biz/
  3. Resolving www.cyberciti.biz... 74.86.144.194
  4. Connecting to www.cyberciti.biz|74.86.144.194|:80... connected.
  5. HTTP request sent, awaiting response... 200 OK
  6. Length: unspecified [text/html]
  7. Saving to: 'index.html.1'
  8. index.html.1 [ <=> ] 36.17K 115KB/s in 0.3s
  9. 2015-08-03 23:25:18 (115 KB/s) - 'index.html.1' saved [37041]

-i 选项使 env 命令完全忽视它继承的环境。但是,它并不会阻止你的命令(例如 wget 或 curl)设置新的变量。同时,也要注意运行 bash/ksh shell 的副作用:

  
  
  1. env -i env | wc -l ## 空的 ##
  2. # 现在运行 bash ##
  3. env -i bash
  4. ## bash 设置了新的环境变量 ##
  5. env | wc -l
例子:设置一个环境变量

语法如下:

  
  
  1. env var=value /path/to/command arg1 arg2 ...
  2. ## 或 ##
  3. var=value /path/to/command arg1 arg2 ...

例如设置 http_proxy:

  
  
  1. env http_proxy="http://USER:PASSWORD@server1.cyberciti.biz:3128/" /usr/local/bin/wget www.cyberciti.biz

via: http://www.cyberciti.biz/faq/linux-unix-temporarily-clearing-environment-variables-command/

作者:Vivek Gite 译者:ictlyh 校对:wxy

本文由 LCTT 原创翻译,Linux中国 荣誉推出

来源: https://linux.cn/article-5980-1.html
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值