How to remove package only when no package depend on it?

I'm writing a script to auto install some package and then remove them after the work is done. But in some case, the package may be installed on the system before or is installed as dependency by other packages. So how to remove package only if there is no package depend on it?


Solution 1:

You mau use the command

sudo apt-get autoremove

autoremove is used to remove packages that were automatically installed to satisfy dependencies for some package and that are no more needed.

Solution 2:

Use e.g. dpkg-query to test, if your package is installed already before you install it; see man dpkg-query. As for dependencies, you could use

sudo apt-get autoremove yourpackage1 yourpackage2 ...

to remove the package(s) with its dependencies that are automatically installed and that no leftover package depends on. But it will also remove packages that are unneeded dependencies of some other (removed) packages unrelated to the package you installed. Is that a problem?