Question

Check if variable is numeric or string

Asked by: ahoor

I have a problem in a shell program where I do errorchecking.

I ask a returnvalue from the database, which usually is a number, and this goes to a variable.
Now, I want to know if the returnvalue is a number or a string (the erromessage)

A sample of what I have:

tail -2 $log > $templog
head -1 $templog | read returnstatus

if [ $returnstatus > 0 ]
then
   errorfunction $returnstatus
fi

This goes well when $returnstatus is 0 or 20000 but, of course, not when $returnstatus is for example 'Arithemic overflow'

I also tried

if [ "$returnstatus" > "0" ]

but still no succes.

what I want is something like:

if $returnvalue between 0 and 999999
then
   returnfunction $returnvalue
else
   set returnstatus=123456
   returnfunction  $returnvalue
fi

Or a check if $returnstatus is a number or not, if that is possible.

So, how do I do this in ksh script?
I work om HP-UX.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-11-20 at 04:06:13ID20803847
Tags

numeric

,

check

,

variable

,

string

Topic

Unix Systems Programming

Participating Experts
6
Points
250
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Is there a better 'tail -f' ?
    I have a log file which I monitor using 'tail -f', however the process writing to this file archives it every so often which crashes the tail -f. The archives I think involves moving the file to a different filename and starting a new file. Is there a better command than 't...
  2. Looking for "integrating sqlplus/ksh" resources
    Can someone direct me to some good resources that have examples of integrating sqlplus execution inside a Korn Shell script. I need to: - Pass sqlplus success/fail status back to the ksh. - Trap sql errors in my ksh application and perform "ksh" conditional logic ...
  3. Ksh or
    What is the syntax in Ksh for OR ? I want to do something like this if $x=0 or $x=1 then do something fi

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: liddlerPosted on 2003-11-20 at 04:21:07ID: 9786784

How about?
if [ "$returnstatus" -gt "0" ] && [ "$returnstatus" -lt "999999" ]

 

by: yuzhPosted on 2003-11-20 at 04:49:28ID: 9786919

if [ ${returnstatus} -gt 0 -a ${returnstatus} -lt "999999" ]  ; then

 

by: yuzhPosted on 2003-11-20 at 04:49:49ID: 9786922

if [ ${returnstatus} -gt 0 -a ${returnstatus} -lt 999999 ]  ; then

 

by: ahoorPosted on 2003-11-20 at 05:00:56ID: 9786977

Ok, as a workaround this works.

I still get an error executing the script but it does continue with a good errormessage.

Sample from my script:

tail -2 $log > $templog
head -1 $templog | read returnstatus

echo $returnstatus

if [ "$returnstatus" -gt "0" ] && [ "$returnstatus" -lt "999999" ]
then
   [some script]
else
   returnstatus="160032"
  [some script]
fi

output on screen:
Arithmetic overflow occurred.
./script.ksh[343]: Arithmetic overflow occurred.: syntax error

output in log (nevermind the dutch language):

Er is een fout opgetreden bij het uitvoeren van de interface.
Melding:

Msg 160032, Level 16, State 1:

You can see it does continue with the correct errorvalue, so it does go into the 'else' part of the statement.
If I could get rid if the syntax error it would be great, if not I'll just have to work with this. I'll leave this question open til tomorrow to see if someone has a great idea...

thanx so far.

 

by: ahoorPosted on 2003-11-20 at 05:04:21ID: 9787001

Yuzh your statement does give another syntaxerror:

./import_jaarplan_test2.ksh[343]: overflow: unknown test operator

Otherwise I get the same result as Liddler's solution.

 

by: yuzhPosted on 2003-11-20 at 05:34:39ID: 9787196

which version of HP-UX are you using.

if [ ${returnstatus} -gt 0 -a ${returnstatus} -lt 999999 ]  ; then

should not cause overflow.

Please post your whole script

 

by: yuzhPosted on 2003-11-20 at 06:16:14ID: 9787505

Here's some of the sample code from one of my script. it is runing
everyday under HP-UX:

        CTIME=`date +%Y%m%d%H%M`
        if [ $CTIME -ge $STIME -a $CTIME -lt $ETIME ] ; then
            trap "endlog" 0 1 2 15
        ........
        else
           # do soemthing
        fi

PS: CTIME is a lot bigger than 999999

 

by: mbekkerPosted on 2003-11-20 at 06:25:30ID: 9787581

Hello,

I've put an 'expr' in the following script to determine if the variable is a string or an integer. In this case you can perform other actions whenever an invalid string is returned:

tail -2 $log | head -1 | read returnstatus

expr $returnstatus + 0 >/dev/null 2>&1
if [ $? -ne 0 ]
then
  echo "Invalid returncode: $returnstatus"
  # [some script]
else
  if [ $returnstatus -gt 0 -a $returnstatus -lt 999999 ]
  then
    echo "Valid returncode: $returnstatus"
    # [some script]
  else
    echo "Other returncode: $returnstatus"
    returnstatus="160032"
    # [some script]
  fi
fi

Good luck!

 

by: ahoorPosted on 2003-11-20 at 07:18:08ID: 9788105

Yes! Thanks, I was looking for a function like this...
It works perfect now.

 

by: CuthbertDibbleGrubPosted on 2004-04-15 at 03:08:59ID: 10831632

If you're using the Korn shell, you can define a variable as an integer thus:

typeset -i my_number

and then assign it using:

my_number=`a UNIX command` or my_number=7

If you assign a non-numeric value to the variable, it will assign zero to it instead.  Therefore, you can then test for a numeric value like this:

if [ my_number -gt 0 ]
then
  echo "It's a number!"
else
  echo "It's not a number!"
fi

Note that variables typeset in this way can be used without the need for teh '$' or expr syntax e.g. a=a+1; if [ a -eq 10 ]; then echo "It equals ten."; fi

Shaun.

 

by: JJSmithPosted on 2005-04-07 at 13:59:43ID: 13731120

Adding 0 to a variable is the recognised way of achiving a numeric test. However just for fun, why not delete all digits from the string and test if there is anything left.

eg
if [ -n "`echo "$returnstatus" | tr -d [0-9]`]; then
   echo "Invalid returncode: $returnstatus"
else
   carry on .....
fi

It all depends on how 'perfectionist' or 'anally retentive' we want to be ;-) - this option will return invalid if the returnstatus contains leading or trailing spaces, as a space is not numeric - some of the other options above will not.

Cheers
JJ

 

by: vocogovPosted on 2010-11-03 at 13:54:22ID: 34056702

I figured it out.
expr $userinput + 0 > /dev/null 2>&1
if [ $? -eq 0 ] ; then
  go on with my script stuff
else
  display error message
fi

Am attaching working code.  Still more to be done but this gets me through the error checking.

#! /bin/ksh
# set -x
# This menu reads a control file to gather the latest list of agents
#  then checks to see if the agent is running as a process.
# When displaying the agent list on the screen, it's status is included
#  (running or stopped).
# Until the user exits the program, each time they press the enter key
#  (whether they entered a reply or not) the program loops and provides
#  a current status of the agent processes.
# They choose which agent they'd like to start from the menu.
# Only agents that are not running will be started regardless of what
#  the user selects.
#

while true
do
clear
  echo "Below are agents and their current statuses."
  echo
  echo
  echo "Press ENTER to refresh screen or choose an agent below to stop it. "
  echo "Note: Logging will stay enabled for the tables in the agent. "
  echo
  AGENTCTL=/iway/cdcagent/config/agent.ctl
  proc_count=0
  cat $AGENTCTL |  while read LINE
  do
  case $LINE in
    \#* )   ;;  #comment line-Ignore
       *) PROCESS=`ps -ef | grep iwaycdcagent | grep $LINE | awk '{print $2}'`
          proc_count=`expr $proc_count + 1`
          item_list=`echo $item_list $LINE`
          if [ "$PROCESS" = "" ] ; then
            echo "$proc_count. $LINE - stopped"
          else
            echo "$proc_count. $LINE - Running"
          fi
  esac

  done

  proc_count=`expr $proc_count + 1`  # this sets the next menu item for ALL
  echo "$proc_count. ALL running agents"

  echo "x. Exit"
  echo
  echo Select an item to stop an agent or $proc_count for ALL Agents.
  echo
  echo $MSG
  echo


  read answer1 answer2

lanswer1=`echo $answer1 | tr '[A-Z]' '[a-z]'`
lanswer2=`echo $answer2 | tr '[A-Z]' '[a-z]'`

if [ "$lanswer1" = "x" ] ; then
  break
fi

if [ "$lanswer2" = "" ] || [ "$lanswer2" = "reset" ] ; then

expr $lanswer1 + 0 > /dev/null 2>&1
if [ $? -eq 0 ] && [ "$lanswer1" != "" ] ; then
   lanswer1=`expr $lanswer1 + 0`
    if [ $lanswer1 -lt $proc_count ] ; then
     startitem=`echo "$item_list" | cut -f"$lanswer1"-"$lanswer1" -d" "`
     PROCESS=`ps -ef | grep iwaycdcagent | grep $startitem | awk '{print $2}'`
     if [ "$PROCESS" = "" ] ; then
#      start command here.
      MSG="$startitem starting...press ENTER to refresh status."
     else
      MSG="$startitem already running."
     fi
    elif [ "$lanswer1" -eq "$proc_count" ] ; then # this to start all loop
      proc_loop=1
      while [ $proc_loop -lt $proc_count ]
      do
       startitem=`echo "$item_list" | cut -f"$proc_loop"-"$proc_loop" -d" "`
       PROCESS=`ps -ef | grep iwaycdcagent | grep $startitem | awk '{print $2}'`
        if [ "$PROCESS" = "" ] ; then
          # start command issued here
     echo "this msg to suppress error since command isnt used yet" > /dev/null
        fi
        proc_loop=`expr $proc_loop + 1`
      done
      MSG="starting all agents...press ENTER to refresh status."
    else
      MSG="...Invalid option. Try again."
    fi
  else
    MSG="...Invalid option. Try again."
  fi

else # answer2 not valid
  MSG="...Invalid option $answer2.  Try again."
fi
done

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:

Select allOpen in new window

 

by: vocogovPosted on 2010-11-03 at 13:56:12ID: 34056714

oops.. posted to wrong place.  Ugh.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...