Godzilla74 Godzilla74 - 1 year ago 65
Linux Question

Check version of program and so something in bash

I've created a bash script that runs via a crontab that checks the installed version of nmap on a linux host. The problem is that for some reason, the check is not working correctly and it's always trying to install nmap again and again...

if ! $(nmap --version | grep -q "7.12"); then
wget https://nmap.org/dist/nmap-7.12.tar.bz2 -P /tmp/
cd /tmp && bzip2 -cd nmap-7.12.tar.bz2 | tar xvf -
cd nmap-7.12
./configure --without-zenmap
make install
cd ..
rm nmap-7.12.tar.bz2
rm -rf nmap-7.12

If I check to see if the job is running (which it should once, but never again since the version should match the 2nd time) it is...

$> ps aux | grep nmap
root 27696 15.4 0.3 2940 1464 ? R 16:31 0:00 /bin/bash ./configure --disable-option-checking --prefix=/usr/local --without-zenmap --cache-file=/dev/null --srcdir=. --no-create --no-recursion

Running the check from the command line yields (without -q):

$> nmap --version | grep "7.12"
Nmap version 7.12 ( https://nmap.org )

What is messed up with my script?

Answer Source

ShellCheck says:

Line 2:
if ! $(nmap --version | grep -q "7.12"); then
     ^-- SC2091: Remove surrounding $() to avoid executing output.

The right way to do this is just:

if ! nmap --version | grep -q "7.12"; then 

Your attempt finds the string Nmap version 7.12 ( https://nmap.org ), and because of the $(..) it then tries to run that as a command. This results in an error that you probably should have logged and included in the question:

Nmap: command not found

Since errors are false, the ! makes it true and your code runs everytime.