bash - 如何在 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)
让我们一次一个地看这些例子:
- 您可以通过在字符串周围使用引号将变量设置为字符串。
- 您可以将其设置为 int (也可能是浮点数,但没有亲自使用过)
- 您可以将其设置为布尔值
- 您可以将其设置为命令的输出。该命令位于命令内部:
$(#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
这说明了不同形式之间的区别,但一般来说,您使用 引用变量的值$+variable-name
。执行"SOME_VAR"
或SOME_VAR
仅打印出字符串“SOME_VAR”(即,根本不引用变量)。
$SOME_VAR
和之间的区别在于${SOME_VAR}
,后者允许您在变量之前或之后直接有其他内容时使用它而不会出错。
推荐阅读
- reactjs - React 材料表和 redux 开发工具
- oracle - 执行与编译存储过程
- laravel - 用数组更新多行
- llvm - 如何在 LLVM 中提取 Icmp inst 或 binaryOperator Inst 的目标位置?
- javascript - WebAssembly 中是否有 Javascript 运行时
- javascript - 我收到此错误:未捕获的 ReferenceError: $ is not defined at HTMLInputElement.onkeyup
- java - 在 Android 中的图像上添加圆圈
- ruby - 如何在 Ruby 中将两个 int 变量相乘
- python-3.x - Privnote 套接字服务器不理解请求
- python - 使用请求将图像发布到 Firebase