Search code examples
bashdebianio-redirection

Command output doesn't save to variable in bash


I need save the output of apt-cache show debconf-2.0 to a variable, but however I try, the variable remains blank. debconf-2.0 is a virtual package and when running it in the terminal it returns:

N: Can't select versions from package 'debconf-2.0' as it is purely virtual
N: No packages found

I need to get the command output in a script to see if the package is virtual by grep-ing the output to see if it contains "is purely virtual".

I tried it the normal way:

cmd_output=$(apt-cache show debconf-2.0)
echo "$cmd_output"

But this outputs nothing. Then I tried to grab stderr output with 2>&1:

cmd_output=$(apt-cache show debconf-2.0 2>&1)
echo "$cmd_output"

which still outputs nothing. Another command to know if the package is virtual will also help.

To confirm a non-virtual package would return something to the variable, I tried this with a normal package, and it outputted the info just fine.

cmd_output=$(apt-cache show nano 2>&1)
echo "$cmd_output"

which returns:

Package: nano
Version: 7.2-1
Installed-Size: 2804
Maintainer: Jordi Mallace
...

Note that this is not a duplicate of this question. I already mentioned that I've added 2>&1 to redirect stderr to stdout before asking this question. After asking, I found out an additional -q=0 parameter was needed.


Solution

  • I suggest:

    cmd_output=$(apt-cache -q=0 show debconf-2.0 2>&1)
    echo "$cmd_output"
    

    Output:

    N: Can't select versions from package 'debconf-2.0' as it is purely virtual
    N: No packages found
    

    See: https://unix.stackexchange.com/a/617079/74329