gpt4 book ai didi

bash - 不 "pollute"环境的可来源脚本?

转载 作者:行者123 更新时间:2023-12-04 16:18:06 25 4
gpt4 key购买 nike

考虑这两个脚本:

envSetter.sh:

#!/bin/bash

export ENV_VAR=6
return 3

sourceable.sh:

#!/bin/bash

function main()
{
local var=5
source envSetter.sh
}

main "$@"

unset -f main

envSetter.sh 是一个设置一些变量(并可能执行影响当前 shell(环境)的其他操作)的脚本。我需要创建一个可获取源的脚本,该脚本将获取 envSetter.sh 的源代码,但也会自行清理。 IE。运行 source sourceable.sh 后,我希望我的 shell 设置 ENV_VAR 但我不想设置 main (或任何其他sourceable.sh 使用)定义。

上面的脚本实现了这一点。然而,最重要的是,我希望 sourceable.sh 能够返回 main 返回的任何退出代码。现在,脚本返回 unset -f main 的结果。如果我删除该命令,我的脚本将保留我不想要的定义的 main 函数。如果我尝试使用临时变量:

main "$@"
result=$?

unset -f main

return $result

它将返回我期望的结果,但也会留下我不想要的定义的结果。我也可以根本不使用 main 函数,并将所有代码放在脚本的顶层,但这会从 main 内部暴露更多垃圾(例如 >local var),我也不想要。

有没有办法获取 envSetter.sh 的源代码(即让它在当前 shell 中设置变量),返回 main 返回的内容,而不返回 使用 sourceable.sh 使用的任何内容“污染”我当前的 shell?澄清一下:我想要 envSetter.sh 影响我当前的 shell,但我不想 sourceable.sh到。

最佳答案

如何将 unset 命令隐藏在 main 函数中?像这样:

#!/bin/bash

main() {
unset -f main
local var=5
source envSetter.sh
}

main "$@"

请注意,返回状态只会传播,因为 source envSetter.shmain 中的最后一个命令,它将成为 的返回状态main,同样,由于 main 是脚本中的最后一个命令,因此它将成为脚本的返回状态。

顺便说一句,在本应使用 source 运行的东西上使用 shebang 没有多大意义。我倾向于使用这样的东西:

#!/bin/echo Run this script with the source or . command.

关于bash - 不 "pollute"环境的可来源脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67902853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com