Vous pouvez exécuter des scripts bash dans une étape de compilation pour configurer un certain nombre de workflows, y compris :
Exécuter plusieurs commandes en une seule étape de compilation
Lire à partir du système de fichiers
Intégrer une logique, telle que de nouvelles tentatives ou des conditions
Générer vers le journal, par exemple, en exécutant echo $VARNAME.
Définir le champ script
Cloud Build fournit un champ script que vous pouvez utiliser pour spécifier les scripts shell à exécuter dans une étape de compilation. Le champ script accepte une seule valeur de chaîne.
Vous pouvez ajouter un shebang au début de la valeur de la chaîne pour spécifier le shell à utiliser pour interpréter le script. Par exemple, ajoutez #!/usr/bin/env bash pour spécifier le shell Bash. Si vous ne préfixez pas la chaîne de script par un shebang, Cloud Build utilise #!/bin/sh, qui est le shell sh de base, et non le shell Bash.
Si vous spécifiez script dans une étape de compilation, vous ne pouvez pas spécifier args ou entrypoint dans la même étape.
L'extrait de code suivant illustre le champ 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"}]}
Utiliser des substitutions avec le champ script
Les scripts ne sont pas compatibles directement avec les substitutions, mais ils acceptent les variables d'environnement. Vous pouvez mapper des substitutions à des variables d'environnement, soit automatiquement toutes en même temps, soit manuellement en définissant vous-même chaque variable d'environnement.
Map substitutions automatically
Au niveau de la compilation Pour mapper automatiquement toutes les substitutions sur des variables d'environnement, qui seront disponibles tout au long du build, définissez automapSubstitutions sur true en tant qu'option au niveau du build. Par exemple, le fichier de configuration de compilation suivant montre la substitution $_USER définie par l'utilisateur et la substitution par défaut $PROJECT_ID mappée sur des variables d'environnement:
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"}}
Au niveau de l'étape. Pour mapper automatiquement toutes les substitutions et les mettre à disposition en tant que variables d'environnement en une seule étape, définissez le champ automapSubstitutions sur true à cette étape. Dans l'exemple suivant, seule la deuxième étape affichera correctement les substitutions, car elle est la seule à avoir activé le mappage automatique des substitutions:
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"}
Vous pouvez également rendre les substitutions disponibles en tant que variables d'environnement dans l'ensemble de la compilation, puis les ignorer en une seule étape. Définissez automapSubstitutions sur true au niveau de la compilation, puis définissez le même champ sur false à l'étape où vous souhaitez ignorer les substitutions. Dans l'exemple suivant, même si les substitutions de mappage sont activées au niveau de la compilation, l'ID de projet ne sera pas imprimé à la deuxième étape, car automapSubstitutions est défini sur false à cette étape:
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"}
Map substitutions manually
Vous pouvez mapper manuellement les substitutions sur des variables d'environnement. Chaque variable d'environnement est définie au niveau de l'étape à l'aide du champ env, et le champ d'application des variables est limité à l'étape où elles sont définies. Ce champ accepte une liste de clés et de valeurs.
L'exemple suivant montre comment mapper la substitution $PROJECT_ID à la variable d'environnement BAR:
Si votre script bash est enregistré dans un fichier, stockez-le avec votre source de compilation et référencez ce fichier dans votre fichier de configuration de compilation :
Pour utiliser un script bash sur un fichier alors que bash n'est pas le point d'entrée par défaut de l'image que vous utilisez, ajoutez un champ entrypoint pointant vers bash :
{"steps":[{"name":"bash","args":["echo","I am running a bash command"]}]}
Si l'image que vous utilisez est préinstallée avec bash, mais si bash n'est pas le point d'entrée par défaut, ajoutez un champ entrypoint pointant vers bash. Dans l'exemple ci-dessous, le point d'entrée bash est utilisé pour exécuter des commandes gcloud qui interrogent Cloud Build sur l'état de la compilation, en listant les compilations avec un état d'échec.
{"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"]}]}
L'option -c figurant dans le code ci-dessus permet d'exécuter des commandes multilignes. Toutes les chaînes que vous transmettez après -c sont traitées comme des commandes. Pour en savoir plus sur l'exécution des commandes bash avec -c, consultez la documentation bash.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (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)."]]