使用shell脚本从文件读取值

时间:2017-04-06 11:25:43

标签: git bash shell sed

我有一个Jenkinsfile,我想从shell脚本中读取一些值。

该文件的部分是

-- Jenkinsfile
stage ('Setup Vars') {
  switch(BRANCH_NAME) {
    case 'develop':
      env.ECHO_CHAMBER_BRANCH = 'develop'
      env.HENDRICKS_JS_INTEGRATION_BRANCH = 'master'
      env.FEATURES_BRANCH = 'master'
    break
    case 'master':
      env.ECHO_CHAMBER_BRANCH = 'develop'
      env.HENDRICKS_JS_INTEGRATION_BRANCH = 'master'
      env.FEATURES_BRANCH = 'master'
    break
    default:
      env.ECHO_CHAMBER_BRANCH = 'feature-branch'
      env.HENDRICKS_JS_INTEGRATION_BRANCH = 'feature-branch'
      env.FEATURES_BRANCH = 'feature-branch'
    break
  }
}

我需要在case语句的默认部分中读取分配给env.ECHO_CHAMBER_BRANCHenv.HENDRICKS_JS_INTEGRATIONenv.FEATURES_BRANCH的值,因此在此示例中我希望feature-branch返回对于每个变量。

使用shell脚本,我该如何获取这些值?

1 个答案:

答案 0 :(得分:2)

改进了Signal脚本(用法“ case_to_var filename ”):

case_to_var

#!/bin/sed -nf # Only look at lines ending in ':' /:$/{ # remove leading `case`, spaces, and the ':', and save name. s/.* \|://g h # until the `break` line, recall name, append variable name, # and make it shell-parsable. :foo g N y/./_/ s/'//g s/ = /=/ s/\n.*env//gp /break$/!b foo } 的输出:

case_to_var Jenkinsfile

使输出shell可解析,允许执行和使用它;与谨慎使用develop_ECHO_CHAMBER_BRANCH=develop develop_HENDRICKS_JS_INTEGRATION_BRANCH=master develop_FEATURES_BRANCH=master master_ECHO_CHAMBER_BRANCH=develop master_HENDRICKS_JS_INTEGRATION_BRANCH=master master_FEATURES_BRANCH=master default_ECHO_CHAMBER_BRANCH=feature-branch default_HENDRICKS_JS_INTEGRATION_BRANCH=feature-branch default_FEATURES_BRANCH=feature-branch

一样
eval

输出:

eval $(case_to_var Jenkinsfile)
echo $default_FEATURES_BRANCH $develop_FEATURES_BRANCH

单线版:

feature-branch master