"太多的争论"当我遍历文本文件时

时间:2017-10-10 23:38:50

标签: arrays bash shell scripting iteration

在我的代码中,我收到此错误

test.sh: line 10: [: too many arguments
[ - ] mountnfs.sh is OK
test.sh: line 10: [: too many arguments
[ + ] network-manager is OK
test.sh: line 10: [: too many arguments  
[ + ] networking is OK
test.sh: line 10: [: too many arguments
[ + ] ondemand is OK
test.sh: line 10: [: too many arguments
[ - ] plymouth is OK
test.sh: line 10: [: too many arguments
[ - ] plymouth-log is OK
这些都是Ubuntu 16.04的默认服务,目的是检查本地机器服务的默认值。这是代码:

!/bin/bash 
clear

Ubuntu1604=(acpid alsa-utils anacron apparmor apport avahi-daemon  bluetooth bootmisc.sh brltty checkfs.sh checkroot-bootclean.sh checkroot.sh  console-setup cron cryptdisks cryptdisks-early cups cups-browsed dbus dns-clean grub-common hostname.sh hwclock.sh irqbalance kerneloopskeyboard-setup killprocs kmod lightdm lvm2 lvm2-lvmetad lvm2-lvmpolld mountall-bootclean.sh mountall.sh mountdevsubfs.sh mountkernf.sh mountnfs-bootclean.sh mountnfs.sh network-manager networking ondemand plymouth plymouth-log pppd-dns procps rc.local resolvconf rsync rsyslog saned sendsigs speech-dispatcher thermald udev ufw umountfs umountnfs.sh umountroot unattended-upgrades urandom uuidd whoopsie x11-common)

service --status-all > services.txt

while read SERVICE 
do
    if [ $SERVICE in ${Ubuntu1604[@]} != ${Ubuntu1604[@]} ]; then
    #if [ "${Ubuntu1604[@]}" != "$SERVICE" ]; then 
            echo $SERVICE could be harmful
    else
            echo $SERVICE is OK
    fi

 done < services.txt

我已经有一段时间了,我真的很感激一些帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试:

#!/bin/bash
Ubuntu1604='acpid|alsa-utils|anacron|apparmor|apport|avahi-daemon|bluetooth|bootmisc.sh|brltty|checkfs.sh|checkroot-bootclean.sh|checkroot.sh|console-setup|cron|cryptdisks|cryptdisks-early|cups|cups-browsed|dbus|dns-clean|grub-common|hostname.sh|hwclock.sh|irqbalance|kerneloopskeyboard-setup|killprocs|kmod|lightdm|lvm2|lvm2-lvmetad|lvm2-lvmpolld|mountall-bootclean.sh|mountall.sh|mountdevsubfs.sh|mountkernf.sh|mountnfs-bootclean.sh|mountnfs.sh|network-manager|networking|ondemand|plymouth|plymouth-log|pppd-dns|procps|rc.local|resolvconf|rsync|rsyslog|saned|sendsigs|speech-dispatcher|thermald|udev|ufw|umountfs|umountnfs.sh|umountroot|unattended-upgrades|urandom|uuidd|whoopsie|x11-common'

while read -r service
do
    if [[ $service =~ $Ubuntu1604 ]]
    then
       echo "$service is good."
   else
       echo "$service is bad."
   fi
done <services.txt

在此版本中,$Ubuntu1604是一个正则表达式,这允许我们通过bash&#39; [[命令进行匹配。

实施例

作为样本输入,请考虑:

$ cat services.txt 
acpid
CatVideos
anacron

这会产生输出:

$ bash script.sh
acpid is good.
CatVideos is bad.
anacron is good.