如何在不拆分的情况下在数组中使用字符串变量?

时间:2019-06-17 23:38:53

标签: bash shell

我正在创建一个进行安全搜索的工具。我的打印机检测脚本正在另一个.txt文件(例如“打印机固件版本”)中获取字符串,并使用grep工具检查其是否存在于目标主机网站中。但是我的脚本拆分了这些字符串,并将它们用作不同的变量,例如打印机,固件,版本。我如何才能得到这些字符串而不拆分它们?

   found=(`cat temp.txt`) # <- This line for target
   httarr=(`cat httpport.txt`)
   printer_array=(`cd ..; cat keywords/printerwords.txt`)
   for lo in ${httarr[*]}
   do
     ifacelook=`curl -sSL http://$found:$lo`
     for pr in ${printer_array[*]}
     do
        echo $pr # <-This line is to see incoming variables
        echo $found | grep -o '${pr}' &>/dev/null
        if [ $? -eq 0 ];then
          echo -en "$cyan>$green|${red}printer$green|$cyan>$default This device is a printer check: http://$found:$lo \n"
        fi
     done
   done

Incoming variables:
Printer
Firmware
Version
.
.
.
Variables I want:
Printer Firmware Version
.
.
.

1 个答案:

答案 0 :(得分:2)

您的单词分裂发生者有:

found=(`cat temp.txt`) # <- This line for target
httarr=(`cat httpport.txt`)

(均包含 UUOc (不必要使用cat))

代替使用:

mapfile -t found < temp.txt
mapfile -t httarr < httpport.txt

mapfile(与readarray同义)将从stdin中读取文件的每一行到索引数组中。

不推荐,但您也可以将IFS(内部字段分隔符)设置为仅在换行符上使用:

set -o noglob                 ## disable globbing to protect from * in line
oldifs="$IFS"                 ## save current IFS
IFS=$'\n'                     ## set IFS to newline only
found=( $(< temp.txt) )       ## fill arrays
httarr=( $(< httpport.txt) )
IFS="$oldifs"                 ## restore original IFS
set +o noglob                 ## restore globbing  (thanks to Charles)

仔细检查一下,如果还有其他问题,请告诉我。

相关问题