Skip to content

Instantly share code, notes, and snippets.

@cig0
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cig0/bd4c863dd129c8eeb2b3 to your computer and use it in GitHub Desktop.
Save cig0/bd4c863dd129c8eeb2b3 to your computer and use it in GitHub Desktop.
Validate IP and substitute name's spaces with underscores
# Taken from here: http://stackoverflow.com/questions/13015206/variables-validation-name-and-ip-address-in-bash
#!/bin/bash
read name
name=${name// /_}
read ip
if [[ "$ip" =~ ^([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})$ ]]
then
for (( i=1; i<${#BASH_REMATCH[@]}; ++i ))
do
(( ${BASH_REMATCH[$i]} <= 255 )) || { echo "bad ip" >&2; exit 1; }
done
else
echo "bad ip" >&2
exit 1;
fi
echo "name:$name"
echo "ip:$ip"
# From the same post:
unset name ip; \
while ! [ "$name" ] || ! [ "$ip" ];do
printf "Name: %s\r" $name;
read -p Name:\ var;
[ "$var" ] && name=${var// /_};
printf "IP: %s\r" $ip;
read -p IP:\ var;
iparray=($( IFS=".";echo $var;));
[ ${#iparray[@]} -eq 4 ] && \
[ $iparray -ge 0 ] && [ $iparray -le 255 ] && \
[ ${iparray[1]} -ge 0 ] && [ ${iparray[1]} -le 255 ] && \
[ ${iparray[2]} -ge 0 ] && [ ${iparray[2]} -le 255 ] && \
[ ${iparray[3]} -ge 0 ] && [ ${iparray[3]} -le 255 ] && \
ip=$var;
[ "$name" ] && [ "$ip" ] || echo something wrong...;
done; \
printf "Name: '%s'\nIP: '%s'\n" $name $ip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment