Bash: passing format information to printf

Iv'e got a script with a generic use / error function that displays an error message and then gives information about using the script. I reduced this for discussion in this example:

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

usage "Error:  text1 \ntext2 \ntext3"

This leads to the output:

Error:  text1 \ntext2 \ntext3

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

+4
source share
4 answers

You can use the format %b:

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

and name it like:

usage "Error:  text1 \ntext2 \ntext3"

Output:

Error:  text1
text2
text3

By help printf:

%b  expand backslash escape sequences in the corresponding argument
+4
source

You can handle escape sequences when creating a literal that you pass as an argument using the syntax $'...'.

usage $'Error:  text1 \ntext2 \ntext3'

See ANSI-C Quoting

+3

:

usage() {
  [[ -n "$1" ]] && printf "$1" >&2
}

usage "Error:  text1 \ntext2 \ntext3"
+1

, , usage , :

$ usage() {
    printf %s\\n "$@" >&2
}
$ usage 'Error:  text1' text2 text3
Error:  text1
text2
text3

or make a loop yourself and save usagefrom outputting anything to empty arguments:

usage() {
    for arg; do
        printf %s\\n "$arg" >&2
    done
}

or take a trick from anubhava's answer:

usage() {
    [[ "$@" ]] && printf %s\\n "$@" >&2
}

or without bagism [[:

usage() {
    [ -n "$*" ]] && printf %s\\n "$@" >&2
}
0
source

Source: https://habr.com/ru/post/1605642/


All Articles