Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: passing format information into printf

Tags:

bash

printf

Iv'e got a script with a generalized usage/error function, that prints the error out and then gives the script usage information. I reduced that for purposes of discussion to this example:

usage() {
  test -n "$1" && printf "\n %s" "$1" >&2
}

usage "Error:  text1 \ntext2 \ntext3"

This produces the output:

Error:  text1 \ntext2 \ntext3

I wanted each set of text to be on a separate line. How do I do that?

like image 817
Ray Avatar asked Feb 10 '23 03:02

Ray


1 Answers

You can use %b format:

usage() { [[ $@ ]] && printf "%b\n" "$@"; }

and call it as:

usage "Error:  text1 \ntext2 \ntext3"

Output:

Error:  text1
text2
text3

As per help printf:

%b  expand backslash escape sequences in the corresponding argument
like image 144
anubhava Avatar answered Feb 20 '23 19:02

anubhava