英文:
How can I tell if a variable was exported or not in zsh (or bash)?
问题
在终端上,如何轻松区分以下两种情况:
- 一个shell变量:
foo=foovalue
和
- 一个导出的环境变量:
export bar=barvalue
,可供子进程使用?
我知道set
和env
命令。set
报告了两种情况,但没有指示哪个是哪个。env
不报告1)。
示例终端会话
(在zsh + macOS上,但这不应该太重要):
$foo=foovalue
$export bar=barvalue
$set | egrep "^foo|^bar"
bar=barvalue
foo=foovalue
$env | egrep "^foo|^bar"
bar=barvalue
有没有办法看到foo
和bar
,但也指示foo
是一个仅在bash中可见的变量,对于像Python或Ruby脚本这样的子进程将不可见?通常,当我的脚本看不到我期望的内容时,我最终会查找我的shell脚本,查找变量是在哪里定义的。这样做虽然有效,但效率不高。
英文:
On the terminal how can I easily distinguish between
- a shell variable:
foo=foovalue
and
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论