【问题标题】:Need help figuring out why this shell code is not working [duplicate]需要帮助弄清楚为什么这个 shell 代码不起作用 [重复]
【发布时间】:2021-03-03 04:44:52
【问题描述】:

好的,我需要帮助找出为什么此代码不起作用,我已在代码下方列出了我的问题。

#!/bin/bash

if [ "$1" == "" ]
then
        echo "You forgot an IP adress!"
        echo "Syntax: ./ipsweep.sh xxx.xxx.x"

else
        for ip in `seq 1 254`; do
        ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
        done
fi

现在当我运行命令./ipsweeper.sh 时,即使输入什么也没有,程序仍然运行。请帮助看不到它失败的地方。

【问题讨论】:

    标签: bash


    【解决方案1】:

    这个:

    if [ "$1" == "" ]
    

    应该改为:

    if [ -z "$1" ]
    

    如果字符串长度为零,-z 为真。

    ==[[ ]] 一起使用,而=[ ] 一起使用。

    您可以在How to Compare Strings in Bash 中阅读有关 bash 字符串比较的更多信息。

    【讨论】:

      【解决方案2】:

      您还可以检查...

      pingit(){
      ping -c1 ${1}
      }
      
      if [ ${#} -gt 0 ]
      then
          pingit ${1}
      fi
      

      ...参数的数量。然后你可以在没有参数的情况下获取它或使用它与参数......

       # . pingit.sh 
       # pingit localhost
      PING localhost(localhost (::1)) 56 data bytes
      64 bytes from localhost (::1): icmp_seq=1 ttl=64 time=0.058 ms
      
      --- localhost ping statistics ---
      1 packets transmitted, 1 received, 0% packet loss, time 0ms
      rtt min/avg/max/mdev = 0.058/0.058/0.058/0.000 ms
       # sh pingit.sh localhost
      PING localhost(localhost (::1)) 56 data bytes
      64 bytes from localhost (::1): icmp_seq=1 ttl=64 time=0.031 ms
      
      --- localhost ping statistics ---
      1 packets transmitted, 1 received, 0% packet loss, time 0ms
      rtt min/avg/max/mdev = 0.031/0.031/0.031/0.000 ms
      

      【讨论】:

        猜你喜欢
        • 2013-11-21
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多