简体   繁体   English

BASH:重置某些脚本使用的变量

[英]BASH: reset the variables used by certain script

A trivial situation - the script has finished it's execution, and all the variables used on it's way remained. 琐碎的情况-脚本已完成其执行,并且保留了其使用的所有变量。 I'm looking for a way the script could unset all used by it variables ONLY, as there are many other scripts setting their stuff... 'exec bash' is not an option. 我正在寻找一种方法,该脚本只能取消设置所有由其使用的变量,因为还有许多其他脚本在设置其内容...“ exec bash”不是一种选择。 EG from my imagination: 从我的想象中得出的EG:

function setVariables { 
 A="~/"
 B=$(du -sh /smth)
 C="tralala"
}
setVariables

function cleanup {
 readarray -t args < <(setVariables)
 set -u "${args[@]}"
}
cleanup

How to achieve this? 如何实现呢?

Like already suggested in comments, the trivial solution is to put the commands in a script instead of in a function. 就像注释中已经建议的那样,简单的解决方案是将命令放在脚本中而不是函数中。 The script runs in a subprocess with its own environment, and doesn't change anything in the parent. 该脚本在具有自己环境的子进程中运行,并且不会在父进程中进行任何更改。 When the child finishes, nothing from its environment is left. 孩子完蛋后,周围的环境就一无所有。

If you need to use a function, Bash has a local keyword which makes the variable's scope local to the current function. 如果您需要使用一个函数,Bash有一个local关键字,它使变量的作用域对于当前函数而言是局部的。 When the function ends, all variables are reset to their state from before the function ran (unset if they were unset, previous value if they were set). 函数结束后,所有变量将从函数运行之前重置为它们的状态(如果未设置则为unset,如果设置则为先前值)。

If you want to set variables and have them set outside of a function, but have a simple way to revert them to their original value, you really have to build that yourself. 如果要设置变量并将其设置在函数外部,但是有一种简单的方法将其还原为原始值,则实际上必须自己构建该变量。 Look at how Python's virtualenv does it, for example (a common and popular example, though not necessarily the absolutely most robust) -- it basically writes out the previous values to the definition of the deactivate command which disables the virtual environment and (attempts to) return things to the way they were before you ran activate . 例如,看看Python的virtualenv是如何做到的(这是一个常见且流行的示例,尽管不一定绝对是最可靠的)-它基本上将先前的值写到了deactivate命令的定义中,该命令禁用了虚拟环境,并且( )将事物恢复为activate前的状态。

# bash 4+ only!
setVariables () { 
   declare -A _setvariables_old=([A]="$A" [B]="$B" [C]="$C")
   A="~/"
   B=$(du -sh /smth)
   C="tralala"
}
setVariables
:
cleanup () {
   local var
   for var in "${!_setvariables_old[@]}"; do
       printf -v "$var" "%s" "${_setvariables_old[$var]}"
   done
   unset _setvariables_old
}

This leaks slightly (what if _setvariables_old is a variable you want to preserve!?) and doesn't know how to unset things; 这会稍微泄漏(如果_setvariables_old是要保留的变量呢_setvariables_old ),并且不知道如何取消设置。 it just reverts to an empty string if something was unset before you started. 如果在开始之前未设置任何内容,它只会恢复为空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM