Prev: Parsing "for" clause
Next: read multiple fields separated by : and fields separated by , in loop stored in $var
From: Decare on 13 Mar 2010 02:48 Is there any to determine whether a string is a integer or not? For example, read s if [ ... ]; then do something else do another fi -- cogito ergo sum!
From: Ivan Shmakov on 13 Mar 2010 03:04 >>>>> Decare <decare(a)yeah.net> writes: > Is there any to determine whether a string is a integer or not? For > example, > read s > if [ ... ]; then Well, I guess that someone could suggest a way to do so based on some feature built into modern Shells and that I've didn't manage to remember as of yet, but here's the way I'd do it: if echo "$s" | grep -qE '^[[:digit:]]+$' ; then The 'echo' command may be somewhat unsafe, though it apparently doesn't affect this particular code fragment. $ (s=-e ; echo "$s") $ (s=-n ; echo "$s") $ > do something > else > do another > fi -- FSF associate member #7257
From: Janis Papanagnou on 13 Mar 2010 03:42 Decare wrote: > Is there any to determine whether a string > is a integer or not? A "modern shell" way (as mentioned upthread) is, e.g. [[ ${var} == +([0-9]) ]] Janis > For example, > > read s > if [ ... ]; then > do something > else > do another > fi >
From: Stephane CHAZELAS on 13 Mar 2010 05:03 2010-03-13, 06:48(-01), Decare: > > Is there any to determine whether a string > is a integer or not? For example, > > read s > if [ ... ]; then > do something > else > do another > fi For negative or positive decimal integers (not supporting 1e6 or 12. or 1,000,000 or +12 or 0x12...): case $s in ("" | - | *[!0-9-]* | ?*-*) echo no;; (*) echo yes;; esac or: case ${s#-} in ("" | *[!0-9]*) echo no;; (*) echo yes;; esac -- Stéphane
From: SM on 13 Mar 2010 05:42
2010-03-13, Decare skribis: > > Is there any to determine whether a string > is a integer or not? For example, > > read s > if [ ... ]; then > do something > else > do another > fi > I came across this kind of hack: is_int() { printf "%d" $1 > /dev/null 2>&1 return $? } read s if is_int "$s"; then echo "$s is an integer." else echo "$s is not an integer." fi -- kasmra :wq |