如何重构Shell函数以避免重复代码?

时间:2018-07-26 08:47:08

标签: bash shell command-line

我有两个shell脚本,它们依次依次运行。 除BUCKETNAME外,所有参数均相同 有没有什么办法可以重构它,使得只有一个命令我可以运行它。 这是我要执行的两个命令。

命令1

jsonDumpFL()
{
  cat <<EOF
{
   "QUEUEURL":"",
   "BUCKETREGION":"us-east-1",
   "FLAGFILE":"",
   "FTPUSERID":"pcfp-test",
   "FTPPATH":"/PCFP/Incr1",
   "FTPPASSWORD":"pcfp-test",
   "PARAMETERSTOREREGION":"us-east-1",
   "ISFTP2S3":"false",
   "FTPSERVER":"11.11.11.11",
   "BUCKETNAME":"FinancialLineItem/FINALSPARK",
   "QUEUEREGION":"",
   "ISSFTPENABLED":"false",
   "LOCALPATH":"path"
}
EOF
}

aws apigateway test-invoke-method --rest-api-id  int1234udj --resource-id  1asde1 --http-method POST --body "$(jsonDumpFL)"

命令2

jsonDumpSEG()
{
  cat <<EOF
{
   "QUEUEURL":"",
   "BUCKETREGION":"us-east-1",
   "FLAGFILE":"",
   "FTPUSERID":"pcfp-test",
   "FTPPATH":"/PCFP/Incr1",
   "FTPPASSWORD":"pcfp-test",
   "PARAMETERSTOREREGION":"us-east-1",
   "ISFTP2S3":"false",
   "FTPSERVER":"11.11.11.11",
   "BUCKETNAME":"Segments/FINALSPARK",
   "QUEUEREGION":"",
   "ISSFTPENABLED":"false",
   "LOCALPATH":"path"
}
EOF
}

aws apigateway test-invoke-method --rest-api-id  int1234udj --resource-id  1asde1 --http-method POST --body "$(jsonDumpSEG)"

2 个答案:

答案 0 :(得分:2)

只需将您的函数重构为采用BUCKETNAME值的一个参数,然后更改函数名称以使其动态化即可。

jsonDump()
{
  cat <<-EOF
{
   "QUEUEURL":"",
   "BUCKETREGION":"us-east-1",
   "FLAGFILE":"",
   "FTPUSERID":"pcfp-test",
   "FTPPATH":"/PCFP/Incr1",
   "FTPPASSWORD":"pcfp-test",
   "PARAMETERSTOREREGION":"us-east-1",
   "ISFTP2S3":"false",
   "FTPSERVER":"11.11.11.11",
   "BUCKETNAME":"$1",
   "QUEUEREGION":"",
   "ISSFTPENABLED":"false",
   "LOCALPATH":"path"
}
EOF
}

现在使用来调用您的函数

"$(jsonDump "FinancialLineItem/FINALSPARK")"

或为

"$(jsonDump "Segments/FINALSPARK")"

答案 1 :(得分:1)

jq是创建动态JSON的更好选择,因为它可以确保正确引用参数。

jsonDump () {
   jq -n --argjson bn "$1" '{
        QUEUEURL: "",
        BUCKETREGION: "us-east-1",
        FLAGFILE: "",
        FTPUSERID: "pcfp-test",
        FTPPATH: "/PCFP/Incr1",
        FTPPASSWORD: "pcfp-test",
        PARAMETERSTOREREGION: "us-east-1",
        ISFTP2S3: "false",
        FTPSERVER: "11.11.11.11",
        BUCKETNAME: $bn,
        QUEUEREGION: "",
        ISSFTPENABLED: "false",
        LOCALPATH: "path"
    }'
}

(如果对象键中不包含任何“特殊”字符,也可以使引号引起来。)