[英]How to use custom variables in gitlab ci/cd?
我正在为 gitlab ci/cd 变量苦苦挣扎。 我看到很多相互矛盾的例子。 无论如何,我想知道的是如何在脚本内外使用变量。
例如,在作业配置中,我可以使用 bash 命令在脚本部分分配一个变量吗?
some-job:
variables:
SOME_VAR: ''
script:
- SOME_VAR = $(<file_with_a_line_of_text.txt)
在上述情况下,我不确定我是否可以做到这一点。 但我需要用文件内容(即工件)填充一个变量。 另外,什么时候在变量前面使用“$”? 我看到一些使用这些格式的例子:
"SOME_VAR" #in quotes, no dollar sign
"${SOME_VAR}" #in quotes, with dollar sign and wrapped with curly braces
${SOME_VAR} #no quotes, with dollar sign and wrapped with curly braces
$SOME_VAR #i.e. without the double quotes or curly braces
SOME_VAR #i.e. without the double quotes, dollar sign, and curly braces
我可以在示例中看到如此多的用法变化,但并不真正知道何时使用每种样式。 而且我在网上找不到一个使用 bash 命令在脚本中设置自定义变量的示例。
当我在 bash 中设置变量时,我总是在=
周围没有空格的情况下这样做:
VAR1="some string"
VAR2=23
VAR3=true
VAR4=$(cat /path/to/file.txt)
让我们一次一个地通过这些示例 go:
$(#command)
。现在让我们使用它们:
echo $VAR1
# some string
echo "This is my variable $VAR1"
# This is my variable some string
echo "This is my variable ${VAR1}"
# This is my variable some string
echo ${VAR1}
# some string
echo "Error code ${VAR2}A"
# Error code 23A
echo "Error code $VAR2A"
# Error code --- Note: the variable $VAR2A dosn't exist
echo "Error code ${VAR2}${VAR1}"
# Error code 23some string
echo VAR1
# VAR1
echo "VAR1"
# VAR1
这说明了不同 forms 之间的区别,但通常,您使用$+variable-name
引用变量的值。 执行"SOME_VAR"
或SOME_VAR
只会打印出字符串“SOME_VAR”(即,根本不引用变量)。
$SOME_VAR
和${SOME_VAR}
之间的区别在于后者允许您在变量之前或之后直接有其他内容时使用它而不会出错。
如何在 gitlab ci/cd 中使用自定义变量?
通常与任何其他 shell 一样。
但请注意gitlab-ci.yml
是一个 yaml 文件,并且 yaml 有特殊的解析。 因为在script:
例如。 - echo bla
与- 'echo bla'
相同,因为在 yaml 中script:
的内容是一个字符串数组,稍后由 shell 吐出。
如何在脚本内外使用变量。
通常就像在任何其他 shell 脚本中一样。
何时使用每种样式
"SOME_VAR" #in quotes, no dollar sign SOME_VAR #ie without the double quotes, dollar sign, and curly braces
当你想要一个字符串SOME_VAR
字面意思
"${SOME_VAR}"
与"$SOME_VAR"
相同。 当您想从字面上SOME_VAR
变量的内容时。
${SOME_VAR} #no quotes, with dollar sign and wrapped with curly braces $SOME_VAR #ie without the double quotes or curly braces
当您想要分词和文件名扩展后的SOME_VAR
变量的内容时。 这意味着SOME_VAR='*'
然后echo "$SOME_VAR"
将打印*
,但echo $SOME_VAR
将打印当前目录中的所有文件。 你通常总是想引用扩展。
如果与其他字符串连接,则使用${SOME_VAR}
形式,例如。 $SOME_VARbla
不是${SOME_VAR}bla
。
不要在您的脚本中使用大写变量 - 更喜欢小写。 优先使用大写变量作为导出变量。 请注意冲突 - COLUMN
PATH
USER
UID
是已使用变量的示例。
我可以使用 bash 命令在脚本部分分配一个变量吗?
Shell 具有空间意识。 var = val
将执行一个名为var
的命令,其中包含两个 arguments =
和val
。 var=val
会将字符串val
分配给名为var
的变量。 做:
- SOME_VAR=$(<file_with_a_line_of_text.txt)
在 gitlab-ci 中,我更喜欢使用cat
以防我想搬到高山。 $(<
是 bash 扩展。
- SOME_VAR=$(cat file_with_a_line_of_text.txt)
在环境中设置提供SOME_VAR
variables: SOME_VAR
。
什么时候在变量前面使用“$”?
当你想触发变量扩展时。 变量扩展用变量名替换变量值。
使用http://shellcheck.net检查您的脚本。 阅读https://mywiki.wooledge.org/BashGuide一个很好的 shell 介绍和https://wiki.bash-hackers.org/scripting 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.