Check for IP validity

后端 未结 13 1446
庸人自扰
庸人自扰 2020-12-05 07:13

How do I check the validity of an IP address in a shell script, that is within the range 0.0.0.0 to 255.255.255.255?

13条回答
  •  爱一瞬间的悲伤
    2020-12-05 07:30

    This single regex should validate only those addresses between 0.0.0.0 and 255.255.255.255:

    #!/bin/bash
    
    ip="1.2.3.4"
    
    if [[ "$ip" =~ ^(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))$ ]]; then
      echo "success"
    else
      echo "fail"
    fi
    

提交回复
热议问题