Search code examples
bashfunctionvariablesshtrim

Trim a certain character from the begin of a variable


I want to trim from the beginning of a variable the characters zero "0".
In the following function, the input is the part of an IP address with values from 0 to 255.

1) when the value is 1 digit number (0-9) end the input is also 1 digit number (0-9) then don't trim anything if it's 2 digit number (00-09) or 3 digit number (000-009) trim 1 or 2 zeros "0" from the start so the output will be (0-9).

2) when the value is 2 digit number (10-99) end the input is also 2 digit number (10-99) then don't trim anything if it's 3 digit number (010-099) trim zero "0" from the start so the output will be (10-99).

3) when the value is 3 digit number (100-255) then don't trim anything.

function SubnetIP () {
while true; do
echo -e '\n\n\e[1;33mInput the IP Number that your Subnet want to start\e[0m\n'
echo -e '\n\e[32mInput only the third (3) section of the IP Range that you want .
(e.g. For Subnet 192.168.224.0 Input 224\e[0m\n'
echo -e '\e[38;5;208mInput a number between 0 and 255\e[0m'
echo -en '\e[95mSubnet IP : \e[0m' ; read -n3 ips ; echo
    [[ $ips =~ ^[0-9]+$ ]] || { echo -e '\n\e[38;5;208mSorry input a number between 0 and 255\e[0m\n' ; continue; }
    if ((ips >= 0 && ips <= 255)); then break ; else echo -e '\n\e[31mNumber out of Range, input a number between 0 and 255\e[0m\n' ; fi

done
echo -e '\n\nIP : '${ips}'\n\n'
}

Solution

  • You're already making sure only digits 0-9 are accepted, so that's good. Pass the validated input value to "expr" to strip leading zeros:

    [[ $ips =~ ^[0-9]+$ ]] || { echo -e '\nSorry input a number ' ... etc.}
    ips=$(expr ${ips})
    if ((ips >= 0 && ips <= 255)); then break ; else echo -e ... etc.