Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Esta página explica como configurar o Cloud Build para executar scripts bash
num passo de compilação. Se for um utilizador recente do Cloud Build, leia os
inícios rápidos e a
vista geral da configuração de compilação primeiro.
Pode executar scripts bash num passo de compilação para configurar vários fluxos de trabalho, incluindo:
Executar vários comandos num passo de compilação.
Ler a partir do sistema de ficheiros.
Incorporar lógica, como novas tentativas ou condições.
Produzir resultados no registo, por exemplo, executar echo $VARNAME.
Usar o campo script
O Cloud Build fornece um campo script que pode usar para especificar scripts de shell a executar num passo de compilação. O campo script aceita um valor de string único.
Pode prefixar o valor da string com um shebang
para especificar a shell que vai interpretar o script. Por exemplo, adicione #!/usr/bin/env bash para especificar a shell Bash. Se não prefixar a string do script com um shebang, o Cloud Build usa #!/bin/sh, que é a shell sh básica, e não a shell Bash.
Se especificar script num passo de compilação, não pode especificar args nem entrypoint no mesmo passo.
O seguinte fragmento demonstra o campo script:
YAML
steps:-name:'bash'script:|#!/usr/bin/env bashecho "Hello World"-name:'ubuntu'script:echo hello-name:'python'script:|#!/usr/bin/env pythonprint('hello from python')
JSON
{"steps":[{"name":"bash","script":"#!/usr/bin/env bash echo 'Hello World'"},{"name":"ubuntu","script":"echo hello"},{"name":"python","script":"#!/usr/bin/env python\nprint('hello from python')\n"}]}
Usar substituições com o campo script
Os scripts não suportam diretamente substituições, mas suportam variáveis de ambiente. Pode mapear substituições para variáveis de ambiente, quer
automaticamente de uma só vez, quer manualmente definindo cada variável de ambiente
por si.
Mapeie substituições automaticamente
Ao nível da criação. Para mapear automaticamente todas as substituições para variáveis de ambiente, que vão estar disponíveis durante toda a compilação, defina automapSubstitutions como true como opção ao nível da compilação. Por exemplo, o ficheiro de configuração de compilação seguinte mostra a substituição $_USER definida pelo utilizador e a substituição $PROJECT_ID predefinida mapeadas para variáveis de ambiente:
YAML
steps:-name:'ubuntu'script:|#!/usr/bin/env bashecho "Hello $_USER"-name:'ubuntu'script:|#!/usr/bin/env bashecho "Your project ID is $PROJECT_ID"options:automapSubstitutions:truesubstitutions:_USER:"GoogleCloud"
JSON
{"steps":[{"name":"ubuntu","script":"#!/usr/bin/env bash echo 'Hello $_USER'"},{"name":"ubuntu","script":"#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'"}],"options":{"automap_substitutions":true},"substitutions":{"_USER":"Google Cloud"}}
Ao nível do passo. Para mapear automaticamente todas as substituições e torná-las disponíveis como variáveis de ambiente num único passo, defina o campo automapSubstitutions como true nesse passo. No exemplo seguinte, apenas o segundo passo mostra as substituições corretamente, porque é o único com o mapeamento de substituições automáticas ativado:
YAML
steps:-name:'ubuntu'script:|#!/usr/bin/env bashecho "Hello $_USER"-name:'ubuntu'script:|#!/usr/bin/env bashecho "Your project ID is $PROJECT_ID"automapSubstitutions:truesubstitutions:_USER:"GoogleCloud"
JSON
{"steps":[{"name":"ubuntu","script":"#!/usr/bin/env bash echo 'Hello $_USER'"},{"name":"ubuntu","script":"#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'","automap_substitutions":true}],},"substitutions":{"_USER":"Google Cloud"}
Além disso, pode disponibilizar as substituições como variáveis de ambiente em toda a compilação e, em seguida, ignorá-las num passo. Defina
automapSubstitutions como true ao nível da compilação e, em seguida, defina o mesmo campo como false no passo em que quer ignorar as substituições. No exemplo seguinte, embora as substituições de mapeamento estejam ativadas ao nível da compilação, o ID do projeto não é impresso no segundo passo, porque automapSubstitutions está definido como false nesse passo:
YAML
steps:-name:'ubuntu'script:|#!/usr/bin/env bashecho "Hello $_USER"-name:'ubuntu'script:|#!/usr/bin/env bashecho "Your project ID is $PROJECT_ID"automapSubstitutions:falseoptions:automapSubstitutions:truesubstitutions:_USER:"GoogleCloud"
JSON
{"steps":[{"name":"ubuntu","script":"#!/usr/bin/env bash echo 'Hello $_USER'"},{"name":"ubuntu","script":"#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'","automap_substitutions":false}],"options":{"automap_substitutions":true},},"substitutions":{"_USER":"Google Cloud"}
Mapeie substituições manualmente
Pode mapear manualmente as substituições para variáveis de ambiente. Todas as variáveis de ambiente são definidas ao nível do passo através do campo env, e o âmbito das variáveis está restrito ao passo onde são definidas. Este campo recebe uma lista de chaves e valores.
O exemplo seguinte mostra como mapear a substituição $PROJECT_ID para a variável de ambiente BAR:
Se tiver o script bash guardado num ficheiro, armazene o ficheiro juntamente com a origem da compilação e faça referência ao ficheiro de script no ficheiro de configuração da compilação:
Para usar um script bash no ficheiro se o bash não for o ponto de entrada predefinido da imagem que está a usar, adicione um campo entrypoint que aponte para o bash:
{"steps":[{"name":"bash","args":["echo","I am running a bash command"]}]}
Se a imagem que está a usar for pré-embalada com bash, mas se bash não for o ponto de entrada predefinido, adicione um campo entrypoint que aponte para bash. No exemplo abaixo, o ponto de entrada bash é usado para executar comandos gcloud que consultam o Cloud Build para obter o estado da compilação, listando as compilações com um estado de falha.
{"steps":[{"name":"gcr.io/google.com/cloudsdktool/cloud-sdk","entrypoint":"bash","args":["-eEuo","pipefail","-c","gcloud builds list > builds.txt\nwhile read line; do\n if grep -q \"FAILURE\" <<< \"$line\"; then\n echo \"$line\"\n fi\ndone < builds.txt"]}]}
A flag -c no código acima é usada para executar comandos de várias linhas. Qualquer string que passe após -c é tratada como um comando. Para mais informações sobre a execução de comandos bash com o -c, consulte a documentação do bash.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-21 UTC."],[[["\u003cp\u003eCloud Build enables the execution of bash scripts within a build step using the \u003ccode\u003escript\u003c/code\u003e field, which can handle multiple commands, filesystem interactions, logic, and logging.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003escript\u003c/code\u003e field accepts a string value prefixed with a shebang (e.g., \u003ccode\u003e#!/usr/bin/env bash\u003c/code\u003e) to specify the desired shell; otherwise, it defaults to \u003ccode\u003e#!/bin/sh\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eSubstitutions can be used in scripts as environment variables by setting \u003ccode\u003eautomapSubstitutions\u003c/code\u003e to \u003ccode\u003etrue\u003c/code\u003e at either the build level or within individual steps, allowing for dynamic values.\u003c/p\u003e\n"],["\u003cp\u003eBash scripts can be executed from files stored with the build source by using the \u003ccode\u003eargs\u003c/code\u003e field, with the option to set an \u003ccode\u003eentrypoint\u003c/code\u003e to \u003ccode\u003ebash\u003c/code\u003e if necessary.\u003c/p\u003e\n"],["\u003cp\u003eYou can run inline bash commands by specifying \u003ccode\u003ebash\u003c/code\u003e as the \u003ccode\u003ename\u003c/code\u003e in a build step and listing commands in the \u003ccode\u003eargs\u003c/code\u003e field, or using an \u003ccode\u003eentrypoint\u003c/code\u003e in conjunction with bash.\u003c/p\u003e\n"]]],[],null,["# Running bash scripts\n\nThis page explains how to configure Cloud Build to run bash scripts\nwithin a build step. If you're new to Cloud Build, read the\n[quickstarts](/build/docs/quickstarts) and the\n[Build configuration overview](/build/docs/build-config) first.\n\nYou can run bash scripts within a build step to configure a number of workflows\nincluding:\n\n- Running multiple commands in one build step.\n- Reading from the filesystem.\n- Building in logic such as retries or conditionals.\n- Outputting to the log, for example, running `echo $VARNAME`.\n\nUsing the `script` field\n------------------------\n\nCloud Build provides a `script` field that you can use to specify\nshell scripts to execute in a build step. The `script` field takes a single string\nvalue.\n\nYou can prefix the string value with a [shebang](https://en.wikipedia.org/wiki/Shebang_%28Unix%29)\nto specify the shell to interpret the script. For example, add `#!/usr/bin/env bash` to [specify the Bash shell](https://hub.docker.com/_/bash). If you don't prefix the script string with a shebang, Cloud Build uses `#!/bin/sh` which is the basic sh shell, not Bash shell.\n\nIf you specify `script` in a build step, you cannot specify `args` or `entrypoint`\nin the same step.\n\nThe following snippet demonstrates the `script` field: \n\n### YAML\n\n steps:\n - name: 'bash'\n script: |\n #!/usr/bin/env bash\n echo \"Hello World\"\n - name: 'ubuntu'\n script: echo hello\n - name: 'python'\n script: |\n #!/usr/bin/env python\n print('hello from python')\n\n### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"bash\",\n \"script\": \"#!/usr/bin/env bash echo 'Hello World'\"\n },\n {\n \"name\": \"ubuntu\",\n \"script\": \"echo hello\"\n },\n {\n \"name\": \"python\",\n \"script\": \"#!/usr/bin/env python\\nprint('hello from python')\\n\"\n }\n ]\n }\n\nUsing substitutions with the `script` field\n-------------------------------------------\n\nScripts don't directly support substitutions, but they support environment\nvariables. You can map substitutions to environment variables, either\nautomatically all at once, or manually by defining every environment variable\nyourself.\n\n### Map substitutions automatically\n\n- **At the build level** . To automatically map all the substitutions to\n environment variables, which will be available throughout the entire build,\n set `automapSubstitutions` to `true` as an option at the build level. For\n example, the following build config file shows the user-defined\n substitution `$_USER` and the default substitution `$PROJECT_ID` mapped to\n environment variables:\n\n ### YAML\n\n steps:\n - name: 'ubuntu'\n script: |\n #!/usr/bin/env bash\n echo \"Hello $_USER\"\n - name: 'ubuntu'\n script: |\n #!/usr/bin/env bash\n echo \"Your project ID is $PROJECT_ID\"\n options:\n automapSubstitutions: true\n substitutions:\n _USER: \"Google Cloud\"\n\n ### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"ubuntu\",\n \"script\": \"#!/usr/bin/env bash echo 'Hello $_USER'\"\n },\n {\n \"name\": \"ubuntu\",\n \"script\": \"#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'\"\n }\n ],\n \"options\": {\n \"automap_substitutions\": true\n },\n \"substitutions\": {\n \"_USER\": \"Google Cloud\"\n }\n }\n\n- **At the step level** . To automatically map all the substitutions and make\n them available as environment variables in a single step, set the\n `automapSubstitutions` field to `true` in that step. In the following\n example, only the second step will show the substitutions correctly,\n because it's the only one with automatic substitutions mapping enabled:\n\n ### YAML\n\n steps:\n - name: 'ubuntu'\n script: |\n #!/usr/bin/env bash\n echo \"Hello $_USER\"\n - name: 'ubuntu'\n script: |\n #!/usr/bin/env bash\n echo \"Your project ID is $PROJECT_ID\"\n automapSubstitutions: true\n substitutions:\n _USER: \"Google Cloud\"\n\n ### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"ubuntu\",\n \"script\": \"#!/usr/bin/env bash echo 'Hello $_USER'\"\n },\n {\n \"name\": \"ubuntu\",\n \"script\": \"#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'\",\n \"automap_substitutions\": true\n }\n ],\n },\n \"substitutions\": {\n \"_USER\": \"Google Cloud\"\n }\n\n Additionally, you can make the substitutions available as environment\n variables in the entire build, then ignore them in one step. Set\n `automapSubstitutions` to `true` at the build level, then set the same\n field to `false` in the step where you want to ignore the substitutions. In\n the following example, even though mapping substitutions is enabled at the\n build level, the project ID will not be printed in the second step, because\n `automapSubstitutions` is set to `false` in that step: \n\n ### YAML\n\n steps:\n - name: 'ubuntu'\n script: |\n #!/usr/bin/env bash\n echo \"Hello $_USER\"\n - name: 'ubuntu'\n script: |\n #!/usr/bin/env bash\n echo \"Your project ID is $PROJECT_ID\"\n automapSubstitutions: false\n options:\n automapSubstitutions: true\n substitutions:\n _USER: \"Google Cloud\"\n\n ### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"ubuntu\",\n \"script\": \"#!/usr/bin/env bash echo 'Hello $_USER'\"\n },\n {\n \"name\": \"ubuntu\",\n \"script\": \"#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'\",\n \"automap_substitutions\": false\n }\n ],\n \"options\": {\n \"automap_substitutions\": true\n },\n },\n \"substitutions\": {\n \"_USER\": \"Google Cloud\"\n }\n\n### Map substitutions manually\n\nYou can manually map the substitutions to environment variables. Every\nenvironment variable is defined at the step level using [the `env`\nfield](/build/docs/build-config-file-schema#env), and the scope of the variables is restricted to the step\nwhere they are defined. This field takes a list of keys and values.\n\nThe following example shows how to map the substitution `$PROJECT_ID` to the\nenvironment variable `BAR`: \n\n### YAML\n\n steps:\n - name: 'ubuntu'\n env:\n - 'BAR=$PROJECT_ID'\n script: 'echo $BAR'\n\n### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"ubuntu\",\n \"env\": [\n \"BAR=$PROJECT_ID\"\n ],\n \"script\": \"echo $BAR\"\n }\n ]\n }\n\nRunning bash scripts on disk\n----------------------------\n\nIf you have your bash script saved in a file, store the file along with\nyour build source, and reference the script file within your build config file: \n\n### YAML\n\n steps:\n - name: 'bash'\n args: ['./myscript.bash']\n\n### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"bash\",\n \"args\": [\n \"./myscript.bash\"\n ]\n }\n ]\n }\n\nTo use a bash script on file if bash is not the default entrypoint of the image\nyou're using, add an `entrypoint` field pointing to bash: \n\n### YAML\n\n steps:\n - name: 'gcr.io/cloud-builders/gcloud'\n entrypoint: 'bash'\n args: ['tools/myScript.sh','--foo']\n\n### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"gcr.io/cloud-builders/gcloud\",\n \"entrypoint\": \"bash\",\n \"args\": [\n \"tools/myScript.sh\",\n \"--foo\"\n ]\n }\n ]\n }\n\nRunning inline bash scripts\n---------------------------\n\nTo run bash commands using the `bash` image, specify `bash` as the `name`\nof the build step, and the command in the args field: \n\n### YAML\n\n steps:\n - name: 'bash'\n args: ['echo', 'I am running a bash command']\n\n### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"bash\",\n \"args\": [\n \"echo\",\n \"I am running a bash command\"\n ]\n }\n ]\n }\n\nIf the image you're using comes prepackaged with `bash` but if `bash` is not the\ndefault entrypoint, add an `entrypoint` field pointing to `bash`. In the example\nbelow, the `bash` entrypoint is used to run `gcloud` commands that query\nCloud Build for build status, listing builds with a failed status. \n\n### YAML\n\n steps:\n - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'\n entrypoint: 'bash'\n args:\n - '-eEuo'\n - 'pipefail'\n - '-c'\n - |-\n gcloud builds list \u003e builds.txt\n while read line; do\n if grep -q \"FAILURE\" \u003c\u003c\u003c \"$line\"; then\n echo \"$line\"\n fi\n done \u003c builds.txt\n\n### JSON\n\n {\n \"steps\": [\n {\n \"name\": \"gcr.io/google.com/cloudsdktool/cloud-sdk\",\n \"entrypoint\": \"bash\",\n \"args\": [\n \"-eEuo\",\n \"pipefail\",\n \"-c\",\n \"gcloud builds list \u003e builds.txt\\nwhile read line; do\\n if grep -q \\\"FAILURE\\\" \u003c\u003c\u003c \\\"$line\\\"; then\\n echo \\\"$line\\\"\\n fi\\ndone \u003c builds.txt\"\n ]\n }\n ]\n }\n\nThe `-c` flag in the code above is used to execute multi-line commands. Any string\nyou pass after `-c` is treated as a command. For more information on running bash\ncommands with `-c`, see the\n[bash documentation](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Invoking-Bash).\n\nWhat's next\n-----------\n\n- Learn how to [start a build manually](/build/docs/running-builds/start-build-manually).\n- Learn how to [automate builds using triggers](/build/docs/automating-builds/create-manage-triggers).\n- Learn how to [configure build step order](/build/docs/configuring-builds/configure-build-step-order).\n- Learn how to [use community-contributed builders and custom builders](/build/docs/configuring-builds/use-community-and-custom-builders)."]]