LinuxQuestions.org
Latest LQ Deal: Complete CCNA, CCNP & Red Hat Certification Training Bundle
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 10-30-2006, 11:19 AM   #1
Fredde87
Member
 
Registered: Aug 2005
Posts: 158

Rep: Reputation: 30
If-then-else number or not?


Trying to make a script test if $ipart1 is a number between 0-255. Whats the easiest way to do this? I thought it would be just to if [ $ipart1 -ge 0 ] && [ $ipart1 -le 255 ]; then..... But if it is not a number or contains a illigal charector the script will spitt out an ugly "[: XXXXXX: bad number". I guess I have to add another && first to check if $ipart1 is a number, how do I do this?



Thanks

Fredde87
 
Old 10-30-2006, 11:51 AM   #2
berbae
Member
 
Registered: Jul 2005
Location: France
Distribution: Arch Linux
Posts: 540

Rep: Reputation: Disabled
I suggest :
if [ $ipart1 -ge 0 ] 2>/dev/null && [ $ipart1 -le 255 ] 2>/dev/null; then.....
to eliminate the error message. This is ugly but simple.
 
Old 10-30-2006, 12:50 PM   #3
matthewg42
Senior Member
 
Registered: Oct 2003
Location: UK
Distribution: Kubuntu 12.10 (using awesome wm though)
Posts: 3,530

Rep: Reputation: 63
Or test for it being numeric first:
Code:
if ! echo "$ipart1" |grep -q '^[0-9][0-9]*$'; then
    echo "ERROR - ipart1 is not numeric"
else
    if [ $ipart1 -ge 1 ] && [ $ipart1 -le 255 ]; then
        echo "ipart1 is in 1-255 range"
    else
        echo "ipart1 is numeric, but out of 1-255 range"
    fi
fi
Of course, if you need to do this test more than once, it makes sense to put it in a function, e.g.
Code:
numeric_and_in_range () {
    # usage:  numeric_and_in_range testvalue lowerbound upperbound
    value="$1"
    lower="$2"
    upper="$3"

    if ! echo "$value" |grep -q '^[0-9][0-9]*$'; then
         return 1
    else
        if [ "$value" -ge "$lower" ] && [ "$value" -le "$upper" ]; then
            # numeric and in range
            return 0
        else
            # numeric but out of range
            return 1
        fi
    fi
}

# And then call it like this

for n in eep 123 234 345 2374632 -123 0; do
    echo -n "testing $n... "
    if numeric_and_in_range "$n" 1 255; then
        echo "ok"
    else
        echo "failure"
    fi
done
The output looks like this:
Code:
testing eep... failure
testing 123... ok
testing 234... ok
testing 345... failure
testing 2374632... failure
testing -123... failure
testing 0... failure
 
Old 10-30-2006, 01:51 PM   #4
soggycornflake
Member
 
Registered: May 2006
Location: England
Distribution: Slackware 10.2, Slamd64
Posts: 249

Rep: Reputation: 31
No need to spawn an instance of grep, assuming you're using a shell that has substituion '${...//...}' syntax.

Code:
if [ -n "${ipart1//[[:digit:]]}" ]; then
   echo "Error: Bad number"
fi
i.e. remove all digits; for a valid number the result is "" (null string)...
 
Old 10-30-2006, 02:10 PM   #5
matthewg42
Senior Member
 
Registered: Oct 2003
Location: UK
Distribution: Kubuntu 12.10 (using awesome wm though)
Posts: 3,530

Rep: Reputation: 63
Quote:
Originally Posted by soggycornflake
No need to spawn an instance of grep, assuming you're using a shell that has substituion '${...//...}' syntax.

Code:
if [ -n "${ipart1//[[:digit:]]}" ]; then
   echo "Error: Bad number"
fi
i.e. remove all digits; for a valid number the result is "" (null string)...
Wonderful! I didn't know about the substitution syntax, ${var/pattern/replace}. You just saved me a lot of headaches, thank you! Wish I'd known about that three years ago...

It's strange - I knew about the suffix and prefix removal expansions %, %%, # and ##... I'm sure I've spend ages scouring the ksh manpage for something like the // expansion. I think I must have had an old ksh (from sunos 4) when I did this - maybe it wasn't existing / documented at that point. Damn Damn Damn!

Better late than never I suppose.
 
Old 10-30-2006, 02:50 PM   #6
soggycornflake
Member
 
Registered: May 2006
Location: England
Distribution: Slackware 10.2, Slamd64
Posts: 249

Rep: Reputation: 31
No sweat.

Wow, sunos must've had a really old version. ksh on Slackware has //, and is getting on a bit:

Code:
(~) ksh --version
  version         sh (AT&T Labs Research) 1993-12-28 o+
I guess they were using ksh88?

Aside: you can also declare variables to be integers with

Code:
typeset -i foo
It's not relevant for this problem (assigning a non-number just results in 0), but it lets you do things like foo+=1 (doesn't work in bash, but ksh and zsh understand it). Of course, this increments foo by 1, so if foo is 11, it becomes 12. In contrast, if foo were a plain string, it would become 111. It also does automatic arithmetic expansion on assignment to that variable (bash does do that). Bash can do the equivalent with: let "foo+=1".

In ksh/zsh, you can also do

Code:
typeset -i N foo
where N is the base. So, if N is 16, the variable will always be printed in hex.

We're getting totally off-topic now, but ksh/zsh can also do floating point arithmetic. For example, to calculate VAT, you might do

Code:
# typeset -F 2 total=$((249*1.175))
# print $total
292.57
(i.e. with -F N, the variable is always printed to N decimal places; the default is 10 if N is omitted).

Alas, bash doesn't understand floating point, so this isn't portable.
 
Old 10-30-2006, 03:30 PM   #7
matthewg42
Senior Member
 
Registered: Oct 2003
Location: UK
Distribution: Kubuntu 12.10 (using awesome wm though)
Posts: 3,530

Rep: Reputation: 63
I actually used the typeset -i thing to detect numeric values at one point - trying to assign to a typeset -i variable and detecting an error in $?. It saved a shell out to an external, even if it was a little ugly.

I don't know what version of ksh it was, and sadly I don't have access to those systems any more. It's a pity, I'd like to verify that the // expansion isn't in that version, or find out if I just missed it somehow.

These days I'm using bash all the time, but I don't think I use many of the features which aren't in ksh since that's what I learned with.
 
Old 10-30-2006, 03:51 PM   #8
soggycornflake
Member
 
Registered: May 2006
Location: England
Distribution: Slackware 10.2, Slamd64
Posts: 249

Rep: Reputation: 31
typeset -i foo="abc" doesn't seem to report any error ($? is 0 whatever you assign). However, I just noticed that let does set $? to 1 on error, e.g.

Code:
# typeset -i foo
# str="abc"
# let "foo=$str"
# echo $?
1
Works in bash, ksh, and zsh. Might be a little more efficient than ${...//...}; then again, it might not?
 
Old 10-30-2006, 05:09 PM   #9
matthewg42
Senior Member
 
Registered: Oct 2003
Location: UK
Distribution: Kubuntu 12.10 (using awesome wm though)
Posts: 3,530

Rep: Reputation: 63
Quote:
Originally Posted by soggycornflake
Works in bash, ksh, and zsh. Might be a little more efficient than ${...//...}; then again, it might not?
I'm sure both are an order of magnitude more efficient than spawning a grep process...
 
Old 10-31-2006, 03:24 AM   #10
Fredde87
Member
 
Registered: Aug 2005
Posts: 158

Original Poster
Rep: Reputation: 30
I only have /bin/sh without substituion so I think I will need to go with matthewg42s solution. But I will bookmark this thread for the future as this could become useful at home sometime.

Thank you all for your help!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Preserving number of links with 'cp'. ( preserve number of links ) Devyn Linux - General 7 09-16-2005 10:07 PM
I'm not a number! dlublink Linux - General 1 03-10-2005 03:37 PM
what is a major number and a minor number ? Menestrel Linux - Newbie 2 10-11-2004 07:53 AM
how do you edit your virtual console number? (or VT number 3) jjorloff1 Linux - General 2 04-03-2004 07:21 PM
why there is a need for minor number and major number for monitor/keyboard in pc? tripathi Solaris / OpenSolaris 1 11-07-2003 09:36 AM


All times are GMT -5. The time now is 07:43 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration