i am trying to create a condition statement that checks if the grep found if a package is installed.
if it is true , then the package should not be installed , and if it is false , then the package should be installed.
i am always getting the same result package is not installed no matter which value i put
please help (in my case the all packages are installed and grep finds a match.
here is code:
chk1=$(yum list installed | grep rpmdevtools)
chk2=$(yum list installed | grep rpmbuild)
chk3=$(yum list installed | grep rpmdev)
if [[ $chk1 -ne 0 && "$chk2" -ne 0 && "$chk3" -ne 0 ]];then
echo "package exists"
sleep 5
else
echo "package doesn't exists installing .."
sleep 5
sudo yum install wget -y
wget http://mirror.centos.org/centos/7/os/x86_64/Packages/rpmdevtools-8.3-5.el7.noarch.rpm
sudo yum install rpmdevtools-8.3-5.el7.noarch.rpm -y
fi
3
Answers
You’re mixing 2 types of results here : result (i.e. displayed text) and return value.
TL;DR
You can verify if the variable
$chkX
is not empty with[[ ! -z ${chkX} ]]
, such as :Or you can do something like this, based on exit codes.
or
When executing in a subshell through $(yum …) you are storing the result (i.e. displayed text) that’s echoed by the command.
For instance:
If you want the return code or exit code, it’s accessible through
$?
.For example:
Note every command changes the exit code.
So accessing twice
$?
will change its value.In your case, you’re testing if the text given by
yum
is mathematically equal to 0:It’s not possible because :
0
.If you run it with test you have various cases of failure:
I’m not familiar with yum, there may be a better way to check, but this will make your if statement work:
I also recommend adding
-w
to grep, to match a whole word.If
yum list installed
is a slow command, consider saving the output in a variable, and grepping that (instead of running it three times):The immediate problem is that
-ne
checks for numeric equality; of course the output fromgrep
is not going to be the number 0, so all of your checks fail.You seem to be overcomplicating things significantly anyway.
yum list installed
optionally accepts a list of packages to check.Notice the convention for diagnostic messages to include the script name
$0
and print to standard error>&2
, and how we avoid the absolutely user-hostile abomination ofsleep
ing in the middle. If you want to give users a chance to decide whether they really want to proceed with the planned action, display a separate prompt (and ideally make it possible to override from the command line, just likeyum install -y
lets you say you don’t want a prompt).