2017-04-06 191 views
0

我有一個Jenkinsfile,我想從shell腳本中讀取一些值。從文件 - 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腳本我怎樣才能得到這些值

任何幫助表示讚賞(任何疑問,請向)

由於

回答

2

改進case_to_var腳本(用法 「case_to_var文件名」):

輸出 case_to_var Jenkinsfile
#!/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 
} 

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 

一行代碼版本:

sed -n '/:$/{s/.* \|://g;h;:foo g;N;y/./_/;s/'"'"'//g;s/ = /=/;s/\n.*env//gp;/break$/!b foo}' Jenkinsfile 
+0

謝謝,你介意後'解釋所有其他選項break'。我可以看到你已經刪除了'env'和'.' – Richlewis

+0

當變量具有'env'時,它不是獨特的,可以被刪除。 – agc

+0

當你說小心使用'eval'會不會有更安全的方法?或者這可以嗎? – Richlewis