Score:0

Command to return package version or empty string

us flag

I'm looking for a simple command that prints the package version, only if the package is installed.

If the package is not installed (or is not a valid package), I want the output to be an empty string.

This is what I've come up with so far. Unfortunately, it only works in cases when the package exists.

dpkg-query --showformat="\${Version}" --show ubuntu-desktop 
1.469

However, when the package does not exist, the output is an error message. I would like the output to be blank or empty in this case.

dpkg-query --showformat="\${Version}" --show ubuntu-desktopX
dpkg-query: no packages found matching ubuntu-desktopX

How can I achieve this?

UPDATE 1

Can we achieve this without using redirection (i.e. 2>/dev/null)?

UPDATE 2

A true/false result would be fine as well, since I can always get the package version using the above, if the result is true.

hr flag
The *output* probably *is* empty; the message `dpkg-query: no packages found matching ubuntu-desktopX` goes to the error stream `stderr`
us flag
Indeed, you are right. Thanks for pointing that out. Nevertheless, let me add the restriction that I do not want to redirect stderr to `/dev/null`. Curious if someone can come up with something.
WinEunuuchs2Unix avatar
in flag
At the end of the day aren't you seeking for True/False rather than Something/Nothing?
us flag
Now that you bring it up, true false would work. (I can always get the package version if the result is true).
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.