You are currently browsing the daily archive for September 23, 2007.

This took much longer for me to nail than I care to admit. How to test if a bash script argument is an integer?

test "$1" -ge 0 -o "$1" -lt 0 2>&- && echo "$1" is an integer

This tests if the value of $1 is greater-than-or-equal-to 0 or is less-than 0. The 2>&- closes test‘s stdout (you could also use 2>/dev/null). Squashing stderr is necessary to mask the “integer expression expected” error that occurs when $1 is not an integer.

Or if you prefer the ‘[‘ syntax:

[ "$1" -ge 0 -o "$1" -lt 0 2>&- ] 2>&- && echo "$1" is an integer

Remember ‘[‘ is actually a command – hence the required space following it – so it also has a stderr that can be closed or redirected.

Advertisements

Categories

September 2007
M T W T F S S
« Aug   Nov »
 12
3456789
10111213141516
17181920212223
24252627282930

Latest del.icio.us

Advertisements