0

I found a great answer on here already (Test if a command outputs an empty string)

I'm trying to apply this to the rpm -e --test command. I want to be able to check for dependencies prior to placing a package in a list for removal. So my simple script looks like this thus far:

for PKG in pkg1 pkg2
do
if [[ $(rpm -e --test $PKG) ]]; then
echo "there are dependencies for $PKG"
else
echo "remove $PKG"
fi
done

However no matter if a package has a dependency or not I always fall through to the else case. Any thoughts on how to go about this differently?

Community
  • 1
  • 1
Matt L.
  • 3
  • 2

1 Answers1

4

The rpm -e --test command will return an exit code indicating whether or not the test was successful. Compare this:

# rpm -e --test openssh
error: Failed dependencies:
  openssh is needed by (installed) connect-proxy-1.100-12.fc23.x86_64
  openssh = 7.2p2-3.fc23 is needed by (installed) openssh-server-7.2p2-3.fc23.x86_64
  openssh = 7.2p2-3.fc23 is needed by (installed) openssh-clients-7.2p2-3.fc23.x86_64
  openssh = 7.2p2-3.fc23 is needed by (installed) openssh-askpass-7.2p2-3.fc23.x86_64
# echo $?
1

Vs:

# rpm -e --test figlet
# echo $?
0

So you can write:

for pkg in pkg1 pkg2; do
  if rpm -e --test $pkg > /dev/null 2>&1; then
    echo "remove package"
  else
    echo "$pkg has dependencies"
  fi
done

If possible, it's generally better to use exit codes for determining the success or failure of a program (because output is often designed to be human-consumable and can change from one release to the next).

larsks
  • 277,717
  • 41
  • 399
  • 399
  • Thank you! I actually tried this, but went about it the wrong way. FYI, you put "rpm -q" rather than "rpm -e" in the if statement. That threw me off for a while :) – Matt L. Apr 28 '16 at 13:35