且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在shell脚本中分配变量

更新时间:2022-11-15 10:07:44

据我所知,不幸的是,bash不支持诸如数组之类的构造,这可能是较早版本4的解决方案。

As far as I know, bash unfortunately does not support constructs like associative arrays, which could be a possible solution, prior version 4.

如果环境的路径看起来都一样,那么您可以这样写。

If the paths for the environments all look like the same, you could write it like this.

#!/bin/sh

base_path="/tmp/in"

dev_env="dev"
simu_env="simu"

run() {
cd /tmp/in/current; java -Dlog4j.configurationFile=/tmp/in/logging/log4j2_Importer.xml -Djava.security.egd=file:///dev/urandom -classpath /tmp/in/runner/lib/*:/tmp/in/lib/* baag.runner.Application --config /tmp/in/config/import.$1.properties.TODO --workflow import --inputDir "$base_path/$1"
}

mode=$1

case "$mode" in
    "$dev_env" | "$simu_env" ) 
        run "$mode" 
        ;;
    *)  echo "error: invalid mode" >&2
        exit 1
        ;;
esac

注意:在此实现中,您必须通过 dev simu 而不是整个路径。如果需要通过完整的路径,则必须更改 $ dev_env | $ simu_env) $ base_path / $ dev_env | $ base_path / $ simu_env)

Note: In this implementation you would have to pass dev or simu to the script instead of the whole path. If you need to pass the complete path you have to change the "$dev_env" | "$simu_env" ) to "$base_path/$dev_env" | "$base_path/$simu_env" )

更新

假设路径结构和环境是固定的,则可以使用简单的正则表达式提取环境并将其作为秒参数传递给函数,如下所示:

Assuming the path structure and the environments are fixed, you can extract the environment with a simple regex and pass it to the function as the seconds parameter, like so:

#!/bin/sh

dev_path="/data/etl-dev/in/eurex"
simu_path="/data/etl-simu/in/eurex"
prod_path="/data/etl-prod/in/eurex"

environments="(dev|simu|prod)"

run() {
    cd /tmp/in/current; java -Dlog4j.configurationFile=/tmp/in/logging/log4j2_Importer.xml -Djava.security.egd=file:///dev/urandom -classpath /tmp/in/runner/lib/*:/tmp/in/lib/* baag.runner.Application --config /tmp/in/config/import.$2.properties.TODO --workflow import --inputDir "$1"
}

mode=$1

case "$mode" in
    "$dev_path" | "$simu_path" )
        environment=$(echo $mode | sed -E "s/.*${environments}.*/\\1/")
        run "$mode" $environment
        ;;
    *)  echo "error: invalid mode" >&2
        exit 1
        ;;
esac