Search code examples
bashprintfescaping

How to escape a value returned from a command that contains special symbol in the shell script


I'm working on the shell script that creates a file with .env extension that contains environment variables that I'm getting from azure key vault. The problem is that when I'm fetching a password it contains a special character "%" that is being interpreted as an unknown command with the following message: %N: invalid directive

The file looks like:

#!/bin/zsh

touch vars.env 

printf "PASSWORD=$(az keyvault secret show --name app-PASSWORD --vault-name "my-vault" --query "value";) \n" >>vars.env

and the result in the file (only the part before "%" symbol):

PASSWORD="bKt39f

The question is how to escape it so the whole password would be written in the file instead of a part of it.


Solution

  • You're using printf wrong. Its first argument is a format string, which tells it how to print the actual data (which is in the rest of the arguments). In the format string, % indicates a format specifier, which tells it to insert one of the data arguments (and the stuff immediately after % tells it how to format that data). Use something like this:

    printf 'PASSWORD=%s\n' "$(az keyvault secret show --name app-PASSWORD --vault-name "my-vault" --query "value";)" >>vars.env
    

    or maybe treat the "PASSWORD=" as data rather than part of the format:

    printf '%s\n' "PASSWORD=$(az keyvault secret show --name app-PASSWORD --vault-name "my-vault" --query "value";)" >>vars.env
    

    In both of these, the %s in the format string means "insert the next piece of data as a plain string".