bash - 如何在 gitlab ci/cd 中使用自定义变量?

标签 bash shell gitlab gitlab-ci

我正在为 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(也可能是浮点数,但尚未亲自使用)
  • 您可以将其设置为 bool 值
  • 您可以将其设置为命令的输出。命令在命令中:$(#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}是后者让你在变量之前或之后直接有其他内容时使用它而不会出错。

    关于bash - 如何在 gitlab ci/cd 中使用自定义变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66862537/

    相关文章:

    bash - 当我运行 shell 命令时,有没有办法让我的 emacs 识别我的 bash 别名和自定义函数?

    node.js - 使用 shell 脚本提取 package.json 版本

    node.js - bash:bower:找不到命令,我不知道该怎么办

    linux - 在输出中搜索并从特定行搜索到特定行,然后再次搜索

    linux - | 中的字符串值awk 中分隔字段被拆分到右侧

    continuous-integration - 如何将标准错误重定向到 GitLab 运行程序中的标准输出

    docker - 在一个容器中运行nginx以在另一个容器中代理传递Gitlab

    git - 使用共享脚本并保持最新状态的最有效的 git 工作流程是什么?

    linux - 在 shell 脚本中搜索字符串

    bash - 在 while 循环中丢失环境