简体   繁体   中英

How do i terminate my script if i don't get an expected integer value? - BASH Shell Script

as i explained in the title, i need to terminate the exec. of my script if the input value is not an integer. Im getting the number from a positional parameter. Here is the code:

a=9
kb=0
var=$2
var=${var:3:1}
if [ ${#2} -ne 4 ]
then
    echo "ethN is wrong"
    exit 1
fi
if [ "$var" -gt 10  -o "$var" -lt 0 ]
then
    echo "N is wrong"
    exit 1
else
    echo "N is ok"
fi

when i use this entry:

bash lartc.sh -i eth#

My script is not ending and i want it to because the "#" from eth# is not an integer and this is what i want it to do. (eg of valid input: eth2,eth3,etc...). However, my terminal says to me that "#" was expected to be an int. I'm validating length and that the number must be between 0-9, i just need to validate the type of it. Any ideas? thank you!

If you just want to validate the N in a certain position is an integer, the following approach should be good:

#! /bin/sh
var=$2
result=$(echo ${var} | grep -E "eth[0-9]")

if [ -z "${result}" ]; then 
    echo "N is wrong"
    exit 1
else 
    echo 'N is ok'
fi

If you're using bash, why not just test against [[ $2 =~ "^eth[0-9]$" ]] ? If that is true, you know:

  • The input has four characters because of ^ and $
  • The first three letters are eth
  • The last is a digit

What will you do if someone runs this on a systemd linux and tries to match enp4s0? :P

Use =~ operator to chech whether N is positive integer or not.

stringA =~ regexp stringA matches the extended regular expression regexp. Only available in bash version 3.0 and later. May only be used inside [[...]]. The =~ Regular Expression match operator no longer requires quoting of the pattern within [[ … ]]. http://tldp.org/LDP/abs/html/bashver3.html

var=${var:3}

if [[ ! $var =~ ^[1-9][0-9]*$ ]]
then
    echo "ethN is wrong"
    exit 1
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM