Reputation: 2502
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...
#!/bin/sh
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
make install
cd ..
rm nmap-7.12.tar.bz2
rm -rf nmap-7.12
reboot
fi
If I check to see if the job is running (which it should once, but never again since the version should match the second 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?
Upvotes: 0
Views: 4287
Reputation: 123490
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 every time.
Upvotes: 6