将命令分配给 Zsh 中的变量
Assigning command to a variable in Zsh
我最近切换到 Zsh,我有一些配置 shell 文件要加载到 Zsh 中。但是,Zsh 似乎不允许通过字符串将命令分配给变量。
曾经有效的方法
local git_conf='git config --global'
$git_conf rebase.autosquash true
在 Bash 中,上面的工作正常。但是在 Zsh 中它打印出来:
command not found: git config --global
如果我只是将整个命令写在同一个文件中,它就可以工作,但是如果我将部分命令分配给一个变量,它就不会工作。有解决办法吗?
谢谢,
这个其实已经有人回答了。在对 google 进行尽职调查之前,我问了一点。所以我会在下面写下我的答案。
解决方案
使用eval
函数即可。但这不是最佳实践。为了获得最佳实践,我使用了 shell 函数。
在我的例子中,我有很多重复的配置,这些配置简化了一些输入,所以它不那么冗长。在这种情况下,考虑到每个配置都有一个唯一的键,我进一步选择了配置的关联数组。
declare -A confs
confs=(
rebase.autosquash true
alias.a '!ga() {
if [ $# -eq 0 ]; then
git add .
else
git add "$@"
fi
}; ga'
)
for key value in ${(kv)confs}
do
# this works, however I'd like to stay away from eval whenever possible
# command="specific command that's always the same ${key} ${value}"
# eval ${command}
# best practice
git_config ${key} ${value}
done
git_config() {
git config --global "$@"
}
您希望 shell 在空格上拆分您的“命令”。因此你必须调用它作为
${(z)git_conf} rebase.autosquash true
当然,这是对 shell 变量的误用,并且在这种简单的情况下有效。我想知道你为什么要在这里使用 shell 变量,而不是 - 比如说 - shell 函数。即使使用数组变量也会更加灵活。
您还可以这样做:
local git_conf=(git config --global)
"$git_conf[@]" rebase.autosquash true
我最近切换到 Zsh,我有一些配置 shell 文件要加载到 Zsh 中。但是,Zsh 似乎不允许通过字符串将命令分配给变量。
曾经有效的方法
local git_conf='git config --global'
$git_conf rebase.autosquash true
在 Bash 中,上面的工作正常。但是在 Zsh 中它打印出来:
command not found: git config --global
如果我只是将整个命令写在同一个文件中,它就可以工作,但是如果我将部分命令分配给一个变量,它就不会工作。有解决办法吗?
谢谢,
这个其实已经有人回答了。在对 google 进行尽职调查之前,我问了一点。所以我会在下面写下我的答案。
解决方案
使用eval
函数即可。但这不是最佳实践。为了获得最佳实践,我使用了 shell 函数。
在我的例子中,我有很多重复的配置,这些配置简化了一些输入,所以它不那么冗长。在这种情况下,考虑到每个配置都有一个唯一的键,我进一步选择了配置的关联数组。
declare -A confs
confs=(
rebase.autosquash true
alias.a '!ga() {
if [ $# -eq 0 ]; then
git add .
else
git add "$@"
fi
}; ga'
)
for key value in ${(kv)confs}
do
# this works, however I'd like to stay away from eval whenever possible
# command="specific command that's always the same ${key} ${value}"
# eval ${command}
# best practice
git_config ${key} ${value}
done
git_config() {
git config --global "$@"
}
您希望 shell 在空格上拆分您的“命令”。因此你必须调用它作为
${(z)git_conf} rebase.autosquash true
当然,这是对 shell 变量的误用,并且在这种简单的情况下有效。我想知道你为什么要在这里使用 shell 变量,而不是 - 比如说 - shell 函数。即使使用数组变量也会更加灵活。
您还可以这样做:
local git_conf=(git config --global)
"$git_conf[@]" rebase.autosquash true