13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

egrepを使ってIPアドレスかどうかをチェックするシェルスクリプト

Last updated at Posted at 2015-01-09

概要

引数に指定した値がIPアドレスで無い場合はエラーを出力して終了。

コード

ip_check.sh
#!/bin/bash

IP=$1
IP_CHECK=$(echo ${IP} | egrep "^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")

if [ ! "${IP_CHECK}" ] ; then
    echo [ERROR] ${IP} is not IP Address.
    exit 1
fi

exit 0

使用例

1.1.1.1

ip_check.sh
$ sh ip_check.sh 1.1.1.1
$ 

1.1.1.256

ip_check.sh
$ sh ip_check.sh 1.1.1.256
[ERROR] 1.1.1.256 is not IP Address.

1.1.1.hoge

ip_check.sh
$ sh ip_check.sh 1.1.1.hoge
[ERROR] 1.1.1.hoge is not IP Address.

参考にさせて頂いたページ

IPv4アドレスを正規表現で表す

かなり使えるPHPの正規表現まとめ

更新

@Fool_Yahooman さんのご指摘でオクテットを分ける.(ドット)をエスケープしました。

13
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?