Search code examples
shelldotfiles

How do I correctly escape complex command lines in chezmoi?


I'm chezmoi-ifying my dotfiles, and I feel like this should be simple, but it isn't. I want to take the result of this command line:

system_profiler SPHardwareDataType | grep 'Serial Number (system)' | awk '{print $4}'

and drop it into a variable in chezmoi:

{{- $serialNumber := "Unknown" -}}

{{- if eq .chezmoi.os "darwin" -}}
    {{- $serialNumber := output "sh" "-c" "system_profiler SPHardwareDataType | grep 'Serial Number (system)' | awk '{print $4}'" -}}
{{- end -}}

[data]
    serial_number = {{ $serialNumber | quote }}

Should be simple, but however I escape that "$4" at the end, I get an error.

I'd be happy enough with:

{{- $serialNumber := output "my_command_wrapped_in_a_shell_script.sh" -}}

but I can't find an "official" way for chezmoi to include shell scripts that aren't part of the run_* family.

If someone schools me on the intricacies of escaping, I'll be delighted. I feel this should be a lot simpler than it is.

I'vce tried Google, chatbots, official docs, throwing blackslashes around randomly, banging on the keyboard...


Solution

  • DISCLAIMER: This isn't an answer about the escaping of chezmoi's output command.

    You might not have seen it; the example of chezmoi's ioreg command is about getting the Platform Serial Number on macOS.

    {{ if eq .chezmoi.os "darwin" }}
    {{   $serialNumber := index ioreg "IORegistryEntryChildren" 0 "IOPlatformSerialNumber" }}
    {{ end }}
    

    It should yield the same result as the following with output:

    system_profiler SPHardwareDataType | awk '/Serial Number/ {print $NF}'