使用shell脚本设置环境变量



我想存储一个变量,即使在执行完成后也保持其值。我发现有一种方法可以做到这一点,那就是把变量设为环境变量。但它似乎确实像我想要的那样工作。

我想要这样的。

init() {
if [[ -z $package_version ]]; then
package_version="v.0.0.1"
exoprt package_version
fi
}

让我们假设我运行这段代码将设置一个版本号,但如果它是第二次运行,它不应该执行if块。

我怎样才能做到这一点?

更新:我想创建一个有多个表的sqlite数据库,每个表与不同的配置文件相关联。我希望用户选择一个配置文件或切换配置文件。现在我应该包含这个配置文件信息,如果用户想要获取或输入详细信息到特定的数据库与我想要存储的值,并保持执行完成后的配置文件的帮助。

许多评论提出了合理的担忧,但这里有一些可能"有效"。适合您的情况:

init() {
# We choose to save our persistant variables file in the same directory
# as the script. We could also save them in ~/.config/my-fun-script or
# elsewhere.
local vars_dir="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
local vars_file="${vars_dir}/.vars-package-version.bash"
# If we use a ~/.config/my-fun-script/config.bash file, we need to
# make sure the directory is created.
mkdir -p "$vars_dir"
# Source the variable file if it exists.
if [[ -f "$vars_file" ]]; then
. "$vars_file"
fi
if [[ -z "$package_version" ]]; then
package_version="v.0.0.1"
# Save the variable file. We modify the declare line to add the -g
# option. This ensures that when we source the variable, next time, from
# within this function, it will be a global. That means that it is
# accessible outside this function.
declare -p package_version | sed 's/declare/declare -g/' >"$vars_file"
fi
}

注意设置"export"标记一个变量只意味着它对我们在这个bash会话中运行的程序是可见的。如果您也想要这种行为,只需在If语句中或在其下方添加您的export package_version

公平警告,我解释了提示,好像你想在一个独立的脚本中运行这个,但我可以纠正。另外,我不明白你想用sqlite数据库作为不同的用户配置文件做什么。