Search code examples
stringbashstring-formatting

Bash format string. Substitute placeholders with values.


I would like to format string using linux bash:

"<username>{0}</username><password>{1}</password>".format("user", "pass")

Output:

<username>user</username><password>pass</password>

What is the correct command to do this? I can use any other wildcard instead {0} and {1}


Solution

  • From printf --help:

    -v var    assign the output to shell variable VAR rather than display it on the standard output

    So, what you need to do is just:

    FMT='<username>%s</username><password>%s</password>'
    printf -v VAR "$FMT" user pass