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?

3

1 Answer 1

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:--}"
1
  • Actually, with some echo implementations, echo - outputs an empty line as they use - to mark the end of options. Commented Jan 14, 2015 at 12:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .