【问题标题】:Is there a way to load bash variables dynamically有没有办法动态加载bash变量
【发布时间】:2021-10-22 10:47:49
【问题描述】:

在我的 bash 脚本中,我将为我的环境变量加载两个文件,看起来像这样:

# file1 is default
OR=/User/onns
DESKTOP_DIR=${OR}/Desktop
# file2 is different for each pc
OR=/User/pc1 
# maybe /User/pc2 in another pc
$ source file1
$ source file2
$ echo $OR
/User/pc1
$ echo $DESKTOP_DIR
/User/onns/Desktop

我的问题是有没有办法动态重新加载变量,所以我不需要定义DESKTOP_DIR 两次,只需替换OR,Tkx。

【问题讨论】:

  • . file1 将在当前 shell 中设置 ORDESKTOP_DIR。 bash 的 . 命令类似于 csh 的 source 命令。
  • @JeffHolt 我知道,但这两个命令和我知道的一样,这不是我想问的????
  • 没有。除了某些特殊的内置变量外,所有变量值都是在存储时计算的,而不是在加载时计算的。
  • 如果我明白你在问什么,不要在file1file2 中声明DESKTOP_DIR=${OR}/Desktop,(实际上根本不需要file1),而只能在源代码file2 之后的脚本,例如. file2; DESKTOP_DIR=${OR}/Desktop; echo $DESKTOP_DIR。然后,您将拥有适合每台 PC 的 DESKTOP_DIR。 (注意.source 的同义词)还要注意,赋值应该是DESKTOP_DIR="$OR/Desktop"(双引号,当下一个字符是'/' 时,不需要用${...} 保护。保护没有伤害,但应该使用双引号)
  • @DavidC.Rankin 但是如果我有很多变量怎么办?我使用 file1 和 file2 因为我有多个变量用于多个 bash 脚本,我不能在每个脚本中声明它们,谢谢你的回复顺便说一句。

标签: bash environment-variables


【解决方案1】:

bash 没有动态计算的变量(嗯,除了一些特殊的内置变量,如 $RANDOM)。

一种选择是使用函数而不是变量。 (注意:我建议使用小写或混合大小写的变量名称,以避免与对 shell 和/或其他实用程序具有特殊含义的各种全大写名称发生冲突,因此我将在示例中遵循此约定。另外, 你应该用双引号引用变量引用以避免奇怪的解析,除非在一些情况下,比如普通赋值的右侧。)

# file1 is default
or=/User/onns
desktop_dir() { echo "${or}/Desktop"; }

# file2 is different for each pc
or=/User/pc1
# maybe /User/pc2 in another pc

$ source file1
$ source file2
$ echo "$or"    # Note double-quoting
/User/pc1
$ desktop_dir    # No `echo` here, the function prints the value
/User/onns/Desktop
# You need to use command substitution to *use* the value
$ dosomething with "$(desktop_dir)"

另一个选项是加载默认值秒,并使用the :- option 仅在尚未定义时更改值。请注意,在这种形式中,必须在每个 PC 覆盖之后应用默认值(以便切换两个文件)。

# Here file1 is different for each pc
or=/User/pc1
# maybe /User/pc2 in another pc

# ...and file2 contains the defaults
or=${or:-/User/onns}
desktop_dir=${desktop_dir:-${or}/Desktop}

$ source file1
$ source file2
$ echo "$or"
/User/pc1
$ echo "$desktop_dir"
/User/onns/Desktop

您也可以使用the := option 来应用默认值作为扩展的一部分...在这种情况下您不需要显式分配,只需使用: 伪命令忽略结果:

# Again, file2 contains the defaults
: ${or:=/User/onns}
: ${desktop_dir:=${or}/Desktop}

【讨论】:

    猜你喜欢
    • 2016-05-31
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2021-07-27
    • 2017-05-06
    • 2012-05-23
    相关资源
    最近更新 更多