dylanaraps / pure-sh-bible

📖 A collection of pure POSIX sh alternatives to external processes.
MIT License
6.45k stars 281 forks source link

Alternate is_int() and is_float() as one-liners #6

Closed tpoindex closed 4 years ago

tpoindex commented 4 years ago

Hey Dylan,

Great stuff with your pure-sh and pure-bash bibles. Lots of cool stuff in both that I've managed to ignore over many years of slinging shell scripts - no longer!

Here's a small change you might consider. I've tested in dash and bash. Perhaps also include in pure-bash-bible?

Cheers, Tom

My tests:

is_int() {
    # usage: is_int "number"
    [ -n "$1" -a "$1" = "${1## }" ] && printf %d "$1" >/dev/null 2>&1
}
is_float() {
    # Usage: is_float "number"
    [ -n "$1" -a "$1" = "${1## }" ] && printf %f "$1" >/dev/null 2>&1
}

test_is_int() {
    is_int "$1" && echo is an int: $1 || echo not an int: \"$1\"
}
test_is_float() {
    is_float "$1" && echo is a float: $1 || echo not a float: \"$1\"
}
echo should be ints:
test_is_int 0
test_is_int 0000000
test_is_int -0
test_is_int 8375209
test_is_int -2
echo; echo should NOT be ints:
test_is_int "  1"
test_is_int "1 "
test_is_int " 42 "
test_is_int 1a
test_is_int a1
test_is_int -a
test_is_int -
test_is_int nope
test_is_int ""
test_is_int "    "
test_is_int "1 0"
test_is_int "1.0"
test_is_int
echo; echo should be floats:
test_is_float 0
test_is_float 0000000
test_is_float .0000000
test_is_float -0
test_is_float -0.000000
test_is_float 0e0
test_is_float 1
test_is_float -2
test_is_float .1
test_is_float 2.7
test_is_float -0
test_is_float -1.
test_is_float .0009e2
test_is_float 2e3
test_is_float 4.3E4
test_is_float 4e-2
echo; echo should NOT be floats:
test_is_float " 1"
test_is_float "1 "
test_is_float a
test_is_float -a
test_is_float -
test_is_float -n
test_is_float 837-5209
test_is_float ""
test_is_float "    "
test_is_float "1.0  "
test_is_float "  1.0"
test_is_float "1 0"
test_is_float nope
test_is_float 192.168.0.1
test_is_float a1
test_is_float 1a
test_is_float 1eieio
test_is_float
dylanaraps commented 4 years ago

Thanks for the PR. :+1:

There are some lint errors to fix:

warning: Prefer [ p ] && [ q ] as [ p -a q ] is not well defined. [SC2166]
note: Double quote to prevent globbing and word splitting. [SC2086]

Your one liners also change what the functions return (they should return 0 for success and 1 for error). Never-mind!

dylanaraps commented 4 years ago

I've pushed modifications of this method to master, thanks for the PR! :+1:

https://github.com/dylanaraps/pure-sh-bible#check-if-a-number-is-a-float