soohoo.io

Why I Use Printf Over Echo

November 17, 2021

While echo is the more widely known command for printing text to standard out, I have found behavior and documentation inconsistencies in its varying implementations1.

macOS echo man page: macOS echo man page

Ubuntu echo man page: ubuntu echo man page

In addition, it’s default behavior can cause unintended results when combined with character sensitive commands like base64. Here are a few use cases where echo has caused some trouble for me.

  1. Base64 encoding credentials to put into secret management (Hashicorp Vault, kubernetes, etc.)

    #!/usr/bin/env bash
    
    PASSWORD="supersecretpassword"
    
    # echo output
    echo "${PASSWORD}" | base64
    c3VwZXJzZWNyZXRwYXNzd29yZAo=
    
    # printf output
    printf "${PASSWORD}" | base64
    c3VwZXJzZWNyZXRwYXNzd29yZA==

    Echo appends a newline to the end of your output which will be passed in the output piped to the base64 command and also appear in the base64 encoded output.

  2. Doing script output

    Desired output

    one line
    two line
    three line
    four
    #!/usr/bin/env bash
    
    INPUT="one line\ntwo line\nthree line\nfour"
    
    # echo output
    echo "${INPUT}"
    one line\ntwo line\nthree line\nfour
    
    # printf output
    printf "${INPUT}"
    one line
    two line
    three line
    four

    The desired output can be achieved using echo with the -e argument, but as shown in the screenshots above, it’s not always documented.


© 2020-2023 Stephen SooHoo