歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 如何在 Linux 上運行命令前臨時清空 Bash 環境變量

如何在 Linux 上運行命令前臨時清空 Bash 環境變量

日期:2017/2/28 13:59:11   编辑:Linux教程

我是個 bash shell 用戶。我想臨時清空 bash shell 環境變量。但我不想刪除或者 unset 一個輸出的環境變量。我怎樣才能在 bash 或 ksh shell 的臨時環境中運行程序呢?

你可以在 Linux 或類 Unix 系統中使用 env 命令設置並打印環境。env 命令可以按命令行指定的變量來修改環境,之後再執行程序。

如何顯示當前環境?

打開終端應用程序並輸入下面的其中一個命令:

  1. printenv

  1. env

輸出樣例:

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-0323: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.17K87.0KB/s in0.4s
  8. 2015-08-0323: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-0323: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.17K115KB/s in0.3s
  9. 2015-08-0323: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:[email protected]:3128/"/usr/local/bin/wget www.cyberciti.biz

via: How To: Temporarily Clear Bash Environment Variables on a Linux and Unix-like System

作者:Vivek Gite 譯者:ictlyh 校對:wxy

本文由 LCTT 原創翻譯,Linux中國 榮譽推出

Copyright © Linux教程網 All Rights Reserved