python -/bin/sh : 1: [: missing ]

标签 python linux

我正在制作一个 python 脚本,它将自动检查计算机上是否安装了 nmap,然后继续运行 nmap。我遇到的一个问题是当它运行时返回 /bin/sh: 1: [: missing ] 我还想知道如何将终端的输出通过管道返回到我的程序中。假设我运行 hostname -I 如何复制输出并在我的脚本中为其分配一个变量名。谢谢代码在下面

import os
import subprocess
def isInstalled(name):
    cmd = """ if ! [ -x "$#(command -v """ + name + """)" ]; then
      echo '0'
      exit 0
    fi"""
    ret = subprocess.check_output(cmd, shell=True).strip()
    if ret == b'0':
        return False
    return True

if isInstalled('nmap'):
print("Nmap is installed")

else:
    print("nmap is uninstalled since quite mode is active auto install will")

最佳答案

看起来你的默认 shell 是没有 test utilitysh可用,所以尝试在要编写的脚本中指定 bash shebang #!/bin/bash:

def isInstalled(name):
    cmd = """#!/bin/bash
    if ! [ -x "$#(command -v """ + name + """)" ]; then
      echo '0'
      exit 0
    fi"""
    ret = subprocess.check_output(cmd, shell=True).strip()
    if ret == b'0':
        return False
    return True

或者您可以使用 double brackets对于 bash 中的 if-else 语句:

if [[ some expression ]]
then
    some code
fi

关于python -/bin/sh : 1: [: missing ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54963761/

相关文章:

C++ linux : dlopen can't find . 所以库

linux - Windows 8 + Git + Composer + SSH

python - 使用 .format() 动态替换 json 值

python - 获取索引范围内行的最大值

python - Numpy 数组添加额外列表

linux - 我如何使用 Perl 调试器的 *supported* 编辑器?

c - Linux 上 pid_t、uid_t、gid_t 的大小

c - 如何追踪 Linux 中应该定义未声明常量的位置

python - 为什么 html2text 模块抛出 UnicodeDecodeError?

python - 对矩阵 python 进行二次采样