问题描述
我注意到检查 PATH、GOPATH 等全局变量是很常见的任务.这就是为什么我想写一个小函数而不是输入很多字母
I've noticed that it's usual task to check global variables like PATH, GOPATH and etc. That's why I want to write small function so instead of typing a lot of letters
echo $PATH
我只能打字
e PATH
函数本身应该很简单
function e() {
echo $($1) # it produces the error "command not found"
}
但是问题是如何替换一个变量来获取PATH的内容?
But the problem is how to substitute a variable to get the content of PATH?
附言我正在使用 zsh
P.S. I'm using zsh
推荐答案
处理此问题的传统 (POSIX) 符号使用 eval
命令,许多人会警告您:
The traditional (POSIX) notation to handle this uses the eval
command, which many will warn you against:
e() {
eval echo \"\$$1\"
}
然而,在 bash 中,您可以使用变量间接:
In bash, however, you can use variable indirection:
function e() {
printf '%s\n' "${!1}"
}
在 zsh 中,您在我最初的回答后添加了它作为标签,间接处理的处理方式不同:
And in zsh, which you added as a tag after my initial answer, indirection is handled differently:
function e() {
printf '%s\n' "${(P)1}"
}
这使用了一个参数扩展标志,您可以在 man zshexpn
中阅读.
This uses a Parameter Expansion Flag which you can read about in man zshexpn
.
P This forces the value of the parameter name to be interpreted as a
further parameter name, whose value will be used where appropriate.
这篇关于在 zsh 中回显全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!