gpt4 book ai didi

YAML 无效 - 可能是引号问题

转载 作者:行者123 更新时间:2023-12-05 00:59:51 27 4
gpt4 key购买 nike

我从 Gitlab CI/CD Pipelines 获得错误信息:yaml invalid。问题是由 .gitlab-ci.yml 脚本的第五行引起的:

   - 'ssh deployer@gitadam.ga \'rm /var/www/html/hosts/production/current/temp__*\''

脚本部分

script:
- 'pwd'
- 'whoami'
- 'ls temp__*'
- 'ssh deployer@gitadam.ga \'rm /var/www/html/hosts/production/current/temp__*\''
- 'if ls temp__* 1> /dev/null 2>&1; then for file in temp__*; do scp $file deployer@gitadam.ga:/var/www/html/hosts/production/current/; done; fi'

如何修复线路?

最佳答案

您可以只保留开头和结尾的单引号,无需使用蛮力将它们全部删除。 这可能会导致其他错误(尽管在您的情况下不是),并且在您的情况下不足以获得您想要的结果。¹

真正的问题是您试图以错误的方式在单引号标量中转义单引号。唯一可以并且需要在单引号标量中转义的字符是单引号。所以这不能通过使用反斜杠来完成,就像你所做的那样,因为反斜杠也需要在单引号标量中转义。

要在单引号标量中转义单引号,您需要加倍/重复它。²

YAML specification措辞略有不同,但效果相同:

The single-quoted style is specified by surrounding “'” indicators. Therefore, within a single-quoted scalar, such characters need to be repeated. This is the only form of escaping performed in single-quoted scalars. In particular, the “\” and “"” characters may be freely used.

所以要更改第 5 行,只需将两个反斜杠更改为单引号即可:

script:
- 'pwd'
- 'whoami'
- 'ls temp__*'
- 'ssh deployer@gitadam.ga ''rm /var/www/html/hosts/production/current/temp__*'''
- 'if ls temp__* 1> /dev/null 2>&1; then for file in temp__*; do scp $file deployer@gitadam.ga:/var/www/html/hosts/production/current/; done; fi'

在 YAML 中的 double 引用标量中,您可以使用反斜杠转义以获得双引号,也可以使用各种特殊字符,或促进 YAML 功能。然而single quotes are not escapable that way .如果您使用双引号,则需要删除第 5 行的反斜杠:

    - "ssh deployer@gitadam.ga 'rm /var/www/html/hosts/production/current/temp__*'"

保留引号的原因有很多。如果您的任何标量都以特殊(对于 YAML)字符开头,则需要引用。标量以字母开头 (A-Za-z) 是不够的:如果标量碰巧有特殊序列,例如注释开始序列 (space + octothorpe) 或值指示符(冒号+空格)序列嵌入,那么你也必须使用引号。

使用单引号比不使用它们更安全,使用它们时您唯一需要知道的是如何转义它们。它们有时可能是多余的,但它们是在 YAM 中定义标量字符串的最简单方法(关于您需要考虑的异常数量)L。


¹如果您删除前导单引号和尾随单引号,您还需要像第 5 行一样删除反斜杠。

²这里的“it”指的是单引号,当然不是整个标量。

关于YAML 无效 - 可能是引号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031039/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com