在zsh(或bash)中,我怎样才能知道一个变量是否已经被导出了呢?

huangapple go评论93阅读模式
英文:

How can I tell if a variable was exported or not in zsh (or bash)?

问题

在终端上,如何轻松区分以下两种情况:

  1. 一个shell变量:foo=foovalue

  1. 一个导出的环境变量:export bar=barvalue,可供子进程使用?

我知道setenv命令。set报告了两种情况,但没有指示哪个是哪个。env不报告1)。

示例终端会话

(在zsh + macOS上,但这不应该太重要):

$foo=foovalue           
$export bar=barvalue    

$set | egrep "^foo|^bar"
bar=barvalue
foo=foovalue

$env | egrep "^foo|^bar"
bar=barvalue

有没有办法看到foobar,但也指示foo是一个仅在bash中可见的变量,对于像Python或Ruby脚本这样的子进程将不可见?通常,当我的脚本看不到我期望的内容时,我最终会查找我的shell脚本,查找变量是在哪里定义的。这样做虽然有效,但效率不高。

英文:

On the terminal how can I easily distinguish between

  1. a shell variable: foo=foovalue

and

  1. an exported environment variable: export bar=barvalue, usable by child processes ?

I know of set and env commands. set reports both cases, without indicating which is which. env does not report 1).

Sample terminal session

(on zsh + macos but that shouldn't matter overmuch):

$foo=foovalue           
$export bar=barvalue    

$set | egrep "^foo|^bar"
bar=barvalue
foo=foovalue

$env | egrep "^foo|^bar"
bar=barvalue

Any way to see both foo and bar, but also indicate that foo is a bash-only variable that will NOT be visible to child processes like a Python or Ruby script? Typically, when my scripts don't see what I expect, what I end up doing is grepping my shell scripts and looking for where the variable was defined. It works, but it's clunky at best.

答案1

得分: 3

使用 declare -p 命令并检查输出。例如:

declare -- BASH="/bin/bash"
declare -x EDITOR="vim"

很明显哪一个是已导出的,哪一个不是。

英文:

Use declare -p and inspect the output. For example:

declare -- BASH="/bin/bash"
declare -x EDITOR="vim"

It's obvious which one is exported or not.

答案2

得分: 0

variable_name="some value"
export variable_name

检查变量是否已导出:

declare -p variable_name | grep -q 'declare -x'
if [ $? -eq 0 ]; then
echo "该变量已导出。"
else
echo "该变量未导出。"
fi

英文:
variable_name="some value"
export variable_name

Check if the variable was exported:

declare -p variable_name | grep -q 'declare -x'
if [ $? -eq 0 ]; then
  echo "The variable was exported."
else
  echo "The variable was not exported."
fi

huangapple
  • 本文由 发表于 2023年8月4日 02:50:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定