diff --git a/provisioner/shell/provisioner.go b/provisioner/shell/provisioner.go index 49ae38579..e73a6f4a1 100644 --- a/provisioner/shell/provisioner.go +++ b/provisioner/shell/provisioner.go @@ -66,6 +66,9 @@ type Config struct { // name of the tmp environment variable file, if UseEnvVarFile is true envVarFile string + // If user provided a shebang for inline scripts + inlineShebangDefined bool + ctx interpolate.Context } @@ -112,16 +115,9 @@ func (p *Provisioner) Prepare(raws ...interface{}) error { } if p.config.InlineShebang == "" { - if p.config.Inline != nil && len(p.config.Inline) > 0 && strings.HasPrefix(p.config.Inline[0], "#!") { - newLineIndex := strings.Index(p.config.Inline[0], "\n") - if newLineIndex == -1 { - newLineIndex = len(p.config.Inline[0]) - } - firstLine := strings.TrimRight(p.config.Inline[0][:newLineIndex], "\r") - p.config.InlineShebang = strings.TrimPrefix(firstLine, "#!") - } else { - p.config.InlineShebang = "/bin/sh -e" - } + p.config.InlineShebang = "/bin/sh -e" + } else { + p.config.inlineShebangDefined = true } if p.config.StartRetryTimeout == 0 { @@ -212,13 +208,22 @@ func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packe // Write our contents to it writer := bufio.NewWriter(tf) - _, _ = writer.WriteString(fmt.Sprintf("#!%s\n", p.config.InlineShebang)) + var shebangWritten bool for _, command := range p.config.Inline { p.config.ctx.Data = generatedData command, err := interpolate.Render(command, &p.config.ctx) if err != nil { return fmt.Errorf("Error interpolating Inline: %s", err) } + if !shebangWritten { + // If the user has defined an inline shebang, use that. + // Or If command does not start with a shebang, use the default shebang. + // else command already has a shebang, so do not write it. + if p.config.inlineShebangDefined || !strings.HasPrefix(command, "#!") { + _, _ = writer.WriteString(fmt.Sprintf("#!%s\n", p.config.InlineShebang)) + } + shebangWritten = true + } if _, err := writer.WriteString(command + "\n"); err != nil { return fmt.Errorf("Error preparing shell script: %s", err) }