Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questa pagina spiega come configurare Cloud Build per eseguire script bash all'interno di un passaggio di compilazione. Se non hai mai utilizzato Cloud Build, leggi prima gli avvii rapidi e la panoramica della configurazione di compilazione.
Puoi eseguire script bash all'interno di un passaggio di compilazione per configurare una serie di flussi di lavoro, tra cui:
Eseguire più comandi in un unico passaggio di compilazione.
Lettura dal file system.
Implementazione di logica come i tentativi di nuovo o i casi.
Output nel log, ad esempio esecuzione di echo $VARNAME.
Utilizzo del campo script
Cloud Build fornisce un campo script che puoi utilizzare per specificare gli script shell da eseguire in un passaggio di compilazione. Il campo script accetta un singolo valore di stringa.
Puoi anteporre al valore della stringa un shebang per specificare la shell che deve interpretare lo script. Ad esempio, aggiungi #!/usr/bin/env bash per specificare la shell Bash. Se non anteponi alla stringa dello script un shebang, Cloud Build utilizza #!/bin/sh, ovvero lo shell sh di base, non lo shell Bash.
Se specifichi script in un passaggio di compilazione, non puoi specificare args o entrypoint
nello stesso passaggio.
Il seguente snippet mostra il 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"}]}
Utilizzare le sostituzioni con il campo script
Gli script non supportano direttamente le sostituzioni, ma supportano le variabili di ambiente. Puoi mappare le sostituzioni alle variabili di ambiente,
in modo automatico tutte contemporaneamente o manualmente definendo ogni variabile di ambiente
da solo.
Mappare le sostituzioni automaticamente
A livello di build. Per mappare automaticamente tutte le sostituzioni alle variabili di ambiente, che saranno disponibili per l'intera build, imposta automapSubstitutions su true come opzione a livello di build. Ad esempio, il seguente file di configurazione di compilazione mostra la sostituzione definita dall'utente $_USER e la sostituzione predefinita $PROJECT_ID mappate alle variabili di 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"}}
A livello di passaggio. Per mappare automaticamente tutte le sostituzioni e renderle disponibili come variabili di ambiente in un unico passaggio, imposta il campo automapSubstitutions su true in quel passaggio. Nell'esempio seguente, solo il secondo passaggio mostrerà le sostituzioni correttamente, perché è l'unico con la mappatura delle sostituzioni automatiche abilitata:
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"}
Inoltre, puoi rendere disponibili le sostituzioni come variabili di ambiente nell'intera compilazione, per poi ignorarle in un unico passaggio. Imposta automapSubstitutions su true a livello di compilazione, quindi imposta lo stesso campo su false nel passaggio in cui vuoi ignorare le sostituzioni. Nel
seguente esempio, anche se le sostituzioni di mappatura sono abilitate a livello di compilazione,
l'ID progetto non verrà stampato nel secondo passaggio perché
automapSubstitutions è impostato su false in quel passaggio:
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"}
Mappare le sostituzioni manualmente
Puoi mappare manualmente le sostituzioni alle variabili di ambiente. Ogni variabile di ambiente viene definita a livello di passaggio utilizzando il campo env e l'ambito delle variabili è limitato al passaggio in cui sono definite. Questo campo accetta un elenco di chiavi e valori.
L'esempio seguente mostra come mappare la sostituzione $PROJECT_ID alla variabile di ambiente BAR:
Se hai salvato lo script bash in un file, archivialo insieme all'origine della build e fai riferimento al file dello script nel file di configurazione della build:
Per utilizzare uno script bash in un file se bash non è il punto di contatto predefinito dell'immagine che stai utilizzando, aggiungi un campo entrypoint che rimandi a bash:
{"steps":[{"name":"bash","args":["echo","I am running a bash command"]}]}
Se l'immagine che utilizzi è precompilata con bash, ma bash non è il punto di contatto predefinito, aggiungi un campo entrypoint che rimandi a bash. Nell'esempio riportato di seguito, il punto di contatto bash viene utilizzato per eseguire comandi gcloud che eseguono query su Cloud Build per lo stato delle build, elencando le build con stato non riuscito.
{"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"]}]}
Il flag -c nel codice riportato sopra viene utilizzato per eseguire comandi multiriga. Qualsiasi stringa
che passi dopo -c viene considerata un comando. Per ulteriori informazioni sull'esecuzione di comandi bash con -c, consulta la documentazione di bash.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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)."]]