检查 Bash 中程序的版本等

God*_*a74 0 linux bash

我创建了一个通过 crontab 运行的 Bash 脚本,用于检查 Linux 主机上安装的 nmap 版本。问题是,由于某种原因,检查无法正常工作,并且它总是尝试一次又一次地安装 nmap...

#!/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
Run Code Online (Sandbox Code Playgroud)

如果我检查作业是否正在运行(应该运行一次,但不会再运行,因为版本应该第二次匹配),它是......

 $> 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
Run Code Online (Sandbox Code Playgroud)

从命令行运行检查会产生(不带 -q):

 $> nmap --version | grep "7.12"
 Nmap version 7.12 ( https://nmap.org )
Run Code Online (Sandbox Code Playgroud)

我的脚本出了什么问题?

tha*_*guy 5

ShellCheck说:

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

正确的方法是:

if ! nmap --version | grep -q "7.12"; then
Run Code Online (Sandbox Code Playgroud)

您的尝试找到了 string Nmap version 7.12 ( https://nmap.org ),并且因此$(..)它尝试将其作为命令运行。这会导致您可能应该记录并包含在问题中的错误:

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

由于错误是错误的,因此它!会变为正确,并且您的代码每次都会运行。