Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Check if variable is numeric or string

Posted on 2003-11-20
13
Medium Priority
?
33,312 Views
Last Modified: 2013-12-26
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.

0
Comment
Question by:ahoor
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +4
13 Comments
 
LVL 18

Expert Comment

by:liddler
ID: 9786784
How about?
if [ "$returnstatus" -gt "0" ] && [ "$returnstatus" -lt "999999" ]
0
 
LVL 38

Expert Comment

by:yuzh
ID: 9786919
if [ ${returnstatus} -gt 0 -a ${returnstatus} -lt "999999" ]  ; then
0
 
LVL 38

Expert Comment

by:yuzh
ID: 9786922
if [ ${returnstatus} -gt 0 -a ${returnstatus} -lt 999999 ]  ; then
0
Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

 
LVL 3

Author Comment

by:ahoor
ID: 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.
0
 
LVL 3

Author Comment

by:ahoor
ID: 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.
0
 
LVL 38

Expert Comment

by:yuzh
ID: 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

0
 
LVL 38

Expert Comment

by:yuzh
ID: 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

0
 
LVL 1

Accepted Solution

by:
mbekker earned 1000 total points
ID: 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!
0
 
LVL 3

Author Comment

by:ahoor
ID: 9788105
Yes! Thanks, I was looking for a function like this...
It works perfect now.

0
 

Expert Comment

by:CuthbertDibbleGrub
ID: 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.

0
 
LVL 6

Expert Comment

by:JJSmith
ID: 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
0
 
LVL 1

Expert Comment

by:vocogov
ID: 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

Open in new window

0
 
LVL 1

Expert Comment

by:vocogov
ID: 34056714
oops.. posted to wrong place.  Ugh.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question