【发布时间】:2017-04-27 10:54:02
【问题描述】:
我在想从脚本外部强制变量值的最佳方法是什么。
现在我正在使用配置文件,但我被要求提供一种从外部强制参数的方法。
实际代码
source "$1.iconf"
// some code that uses variables declared and initialized in the configuration file
这是在该配置文件中以静态方式使用变量的标准情况。我只是运行传递配置文件名的脚本。
./myscript.sh configuration_file
现在在配置文件中定义了一些变量:
Var1 = some value
Var2 = 42
Var3 = "foo"
我应该能做什么:
./myscript.sh configuration_file --Var1="Value defined from outside"
source "$1.iconf"
//Check if some variables are passed from run string
if [ <Passed_From_Run_String_condition> ]; then
//override variables value
//maybe some kind of arguments parsing??
fi
//some code that uses variables declared and initialized in the configuration file (and maybe overridden by passed values)
【问题讨论】:
-
因此,您希望首先根据作为参数传入的变量覆盖脚本中的变量(第二优先顺序),然后您希望通过配置文件中存在的值覆盖变量(第一顺序)优先级)?
-
首先从配置文件中赋值,然后如果某些变量通过参数以不同方式传递,则覆盖该特定变量值
-
添加了一个新答案,应该足以让您入门。
标签: bash shell parameter-passing argparse