如果传递了参数,则从脚本外部强制变量值

Forcing Variable value from outside of the script if argument is passed

我在想从脚本外部强制变量值的最佳方法是什么。

现在我正在使用配置文件,但我被要求提供一种从外部强制参数的方法。


实际代码

source ".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 ".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)

此脚本首先将存储在配置文件中的源变量作为第一个参数传递给脚本,然后它将作为第二个参数变量,这些变量可用于覆盖配置文件中的值或创建新变量,如果它们以前不存在。

foo.sh

#!/bin/bash

source ""
eval "typeset "

echo ${var1}

配置

var1="foo"

运行 脚本:

./foo.sh config var1=yup

输出:

yup

配置文件中的值 "foo" 已替换为通过第二个参数 "yup" 传入的值。如果你想让一个变量只读,所以值不能改变,你可以使用 typeset -r 来定义一个变量。