如何在YAML文件中lint bash脚本
我正在尝试创建一个GitLab CI/CD作业,它从YAML文件中获取一个bash脚本,并检查语法是否正确 我有一个名为.gitlab-ci.template.yml的YAML文件,其内容如下:如何在YAML文件中lint bash脚本,bash,yaml,gitlab-ci,Bash,Yaml,Gitlab Ci,我正在尝试创建一个GitLab CI/CD作业,它从YAML文件中获取一个bash脚本,并检查语法是否正确 我有一个名为.gitlab-ci.template.yml的YAML文件,其内容如下: image: node:10.15.3-alpine stages: - deploy deploy: stage: deploy script: - apk_install - yarn_install - build - deploy .bash:
image: node:10.15.3-alpine
stages:
- deploy
deploy:
stage: deploy
script:
- apk_install
- yarn_install
- build
- deploy
.bash: &bash |
function apk_install() {
apk add jq git curl grep
}
function yarn_install() {
yarn
}
function build() {
echo "Build"
if [ -f ".gitlab-ci.template.yml" ]; then
echo "Just a dumb test for more lines"
fi
}
function deploy() {
echo "Deploy"
}
before_script:
- *bash
我想使用bash部分并测试它。我安装shyaml是为了从YAML文件中获取值,如下所示:
FILE=`cat .gitlab-ci.template.yml | shyaml get-value before_script`
$FILE的内容将是:
- "function apk_install() {\n apk add jq git curl grep\n}\n\nfunction yarn_install()\ \ {\n yarn\n}\nfunction build() {\n echo \"Build\"\n \n if [ -f \".gitlab-ci.template.yml\"\ \ ]; then\n echo \"Just a dumb test for more lines\"\n fi\n}\n\nfunction deploy()\ \ {\n echo \"Deploy\"\n}\n"
然后使用以下命令尝试再次获取有效文件:
echo $FILE | xargs -0 printf '%b\n' | sed 's/\\[[:space:]]\\[[:space:]]/ /g' | sed 's/\\"/"/g' | sed 's/\\[[:space:]]//g'
现在我可以从开头和结尾删除一些字符。但是我想知道有没有更好/更简单的方法?刚刚注意到我应该从shyaml的before_脚本中获得第一个出现。所以我改变了:
FILE=`cat .gitlab-ci.template.yml | shyaml get-value before_script`
致:
您是否考虑过使用yq 下面是一个从文件中获取shell脚本的表达式:
yq -r '.[".bash"]' .gitlab-ci.template.yml
结果就是实际的脚本。现在,你只需要把它输送到一个bash linter上。我为您浏览了这个站点,但找不到bash语法解析器,它通常位于bash文章中。我确实通过谷歌找到了ShellChecker,但我并没有对其进行全面评估,所以请按您认为合适的方式使用
最终,您的代码可能如下所示:
yq -r '.[".bash"]' .gitlab-ci.template.yml | ShellChecker # or use your favorite bash linter
yq -r '.[".bash"]' .gitlab-ci.template.yml | ShellChecker # or use your favorite bash linter