$ verifyIP 1.2.3.4; if [ $? = 0 ]; then echo "is IP"; else echo "is NOT ip"; fi is IP $ verifyIP not_an.IP ; if [ $? = 0 ]; then echo "is IP"; else echo "is NOT ip"; fi is NOT ip $ verifyIP 255.255.255.255 ; if [ $? = 0 ]; then echo "is IP"; else echo "$1 is NOT ip"; fi is IP $ verifyIP 256.255.255.255 ; if [ $? = 0 ]; then echo "is IP"; else echo "$1 is NOT ip"; fi is NOT ip verifyIP 10.255.255.1255 ; if [ $? = 0 ]; then echo "is IP"; else echo "$1 is NOT ip"; fi is NOT ip $ verifyIP a_random_string ; if [ $? = 0 ]; then echo "is IP"; else echo "$1 is NOT ip"; fi is NOT ip $ verifyIP 192.168.1.1 && echo "is IP" || echo "$1 is NOT ip" is IP $ verifyIP the.quick.and.the.not.quick && echo "is IP" || echo "$1 is NOT ip" is NOT ip
Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?
You must be signed in to comment.
commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.
Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.
» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10
Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):
Subscribe to the feed for:
function verifyIP() { octet="(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])"; [[ ${1} =~ ^$octet\.$octet\.$octet\.$octet$ ]] && return 0 || return 1; }
. Next, drop the && return 0... The bash regex test [[ returns 0 or 1 already:function verifyIP() { octet="(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])"; [[ ${1} =~ ^$octet\.$octet\.$octet\.$octet$ ]]; }
. Also the braces around $1 aren't neededfunction verifyIP() { octet="(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])"; [[ $1 =~ ^$octet\.$octet\.$octet\.$octet$ ]]; }
. That's 117 characters rather than 155. . Personally, I'd also make two other changes: octet -> o, and I'd make the variable local to avoid polluting the environment.function verifyIP() { local o='(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])'; [[ $1 =~ ^$o\.$o\.$o\.$o$ ]]; }
function verifyIP() { octet="(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])"; ip4="^$octet\.$octet\.$octet\.$octet$"; [[ ${1} =~ $ip4 ]] && return 0 || return 1; }
verifyIP 10.168.1.1 && echo true || echo false
true IMHO, "10.1" is not an IP address and fails the test.