无法使用“unset -f”来执行 bash 函数当函数名称作为循环中的变量提供时
我正在尝试使用搜索所有函数来取消设置函数,然后循环取消设置它们,但没有运气
非循环方式有效(创建并取消设置 bar_ 的示例)
function bar_ { echo "bar"; }
function_name="bar_"
echo -n "before unset found function: --> "
declare -F $function_name || echo "<not found>"
unset -f $function_name
echo -n "after unset found function: --> "
declare -F $function_name || echo "<not found>"
echo ""
但是,当在循环中取消设置时,它无法删除自身
function foo_ { echo "bar"; }
declare -F | cut -d" " -f3 | grep foo_ | while read function_name
do
echo -n "before under found function: --> "
declare -F $function_name || echo "<not found>"
unset -f ${function_name}
done
echo -n "after unset found function: --> "
declare -F foo_ || echo "<not found>"
echo ""
这是一些范围问题?我尝试将 unset 语句包装在 eval 中,但没有效果。
I am trying to unset function using be searching for all of them and then looping to unset them with no luck
Non loop way works (example where bar_ is created and unset)
function bar_ { echo "bar"; }
function_name="bar_"
echo -n "before unset found function: --> "
declare -F $function_name || echo "<not found>"
unset -f $function_name
echo -n "after unset found function: --> "
declare -F $function_name || echo "<not found>"
echo ""
However when unsetting in a loop, it fails to remove itself
function foo_ { echo "bar"; }
declare -F | cut -d" " -f3 | grep foo_ | while read function_name
do
echo -n "before under found function: --> "
declare -F $function_name || echo "<not found>"
unset -f ${function_name}
done
echo -n "after unset found function: --> "
declare -F foo_ || echo "<not found>"
echo ""
Is this some scope issue? I tried wrapping the unset statement in eval to no effect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的问题不是循环,而是管道。尝试这样:
这使用 bash 进程替换。
或者,您可以在此处使用临时文件或协进程。
The problem here is not the loop, but the pipe. Try it this way:
This uses bash process substitution.
Alternatively you could use a temporary file or a coprocess here.
当您有管道时,管道位于子外壳中,并且不能以变量方式影响外壳。有时很烦人。
您的解决方案:输出命令(回显“unset -f $function_name”),然后评估循环的输出。
When you have a pipeline, the pipeline is in a subshell and cannot affect the outer shell, variable-wise. Very annoying at times.
Your solution: output the commands (echo "unset -f $function_name") and then eval the output of the loop.
使用 Bash 内置的
compgen
您可以避免子 shell 问题。在相关说明中,您可以使用
env -i
关闭单个命令的函数查找。Using the Bash builtin
compgen
you could avoid the subshell issue.On a related note you may turn off function lookup for a single command by using
env -i
.