BASH:IF语句不能处理来自WHILE循环的空字符串

时间:2014-07-22 10:45:19

标签: bash if-statement while-loop

如果命令没有输出,则第一个if语句不起作用。我也尝试评估退出状态,但这也不起作用?

unhide-tcp输出:

# unhide-tcp 
Unhide-tcp 20130526
Copyright © 2013 Yago Jesus & Patrick Gouin
License GPLv3+ : GNU GPL version 3 or later
http://www.unhide-forensics.info
Used options: 
[*]Starting TCP checking

Found Hidden port that not appears in ss: 1025

Found Hidden port that not appears in ss: 1026
[*]Starting UDP checking

脚本:

#!/usr/bin/env bash

unhide-tcp | grep "^Found" | while IFS=":" read -a PORT; do

        if [ -z ${PORT[1]} ]; then

            echo "No hidden ports found."

        elif [ -n ${PORT[1]} ]; then

            echo ${PORT[@]}

        fi

done

3 个答案:

答案 0 :(得分:1)

我认为你只需要:

unhide-tcp | grep "^Found" || echo "No hidden ports found."

它会打印Found Hidden port that not appears in ss: 1025之类的行,如果找不到这些行,脚本会打印"No hidden ports found."而不是 - 因为grep如果找不到匹配则返回非零值。 / p>

如果您想将端口输出压缩成一行,可以使用sedreadarray进行流程替换:

readarray -t PORTS < <(exec unhide-tcp | sed -nr 's|^Found.*: ([0-9]+).*|\1|p')
[[ ${#PORTS[@]} -gt 0 ]] && echo "${PORTS[@]}" || echo "No hidden ports found."

它可以提供类似1025 1026No hidden ports found.的输出。

答案 1 :(得分:0)

最好像这样使用awk

unhide-tcp | awk -F':' '/Found/ && NF==2{c++; print} END{if (c==0) print "No hidden ports found"}'

当我在问题中显示的输入上使用它时,我得到了这个输出:

Found Hidden port that not appears in ss: 1025
Found Hidden port that not appears in ss: 1026

答案 2 :(得分:0)

-z之类的标志需要参数。在您的示例中,$PORT变量的扩展可能为空。用双引号括起变量名。

  

if [-z“$ {PORT [1]}”];然后......