3

I am collecting windows system information using wmic on Linux system. For that purpose, I make various wmic calls and their output is stored in some variables. After required data is collected, I echo those variables, separated by colons, to a file.

But, the problem arises when a variable stores 'null' value, as it does not display anything but just two successive colons.

How can printf be utilized in order to display a 'hyphen' whenever there is a null value stored in a variable?

muru
  • 72,889

1 Answers1

7

You can use this syntax:

"${var:-word}"

This will substitute the value of the variable $var if it is set and not empty and, if not, will substitute with whatever is given by as word. For example:

$ var=foo
$ echo "${var:-bar}"
foo
$ var=
$ echo "${var:-bar}"
bar

So, in your specific case, you can use:

echo "${var:--}"

Or, the safer and more portable:

printf '%s\n' "${var:--}"
terdon
  • 242,166