The Bash FAQ says
If you're validating a simple "string of digits", you can do it with a glob:
# Bash
if [[ $foo = *[!0-9]* ]]; then
echo "'$foo' has a non-digit somewhere in it"
else
echo "'$foo' is strictly numeric"
fi
I thought, "Goody, that looks nice and simple".
I then pasted exactly that into a script, except I added "exit 1" after the first echo and changed $foo
to $1
, so that it looked like
if [[ $1 = *[!0-9]* ]]; then
echo "'$1' has a non-digit somewhere in it"
exit 1
else
echo "'$1' is strictly numeric"
fi
I then tried to run this and got
$ sh foo.sh bar
bar
foo.sh: 6: [[: not found
'bar' is strictly numeric
I'm Bash illiterate, I'm ashamed to say, so I've no idea what could be wrong here. I had the impression, supported by the online Bash manual that the operator for matching with regexes is =~
, but changing that doesn't make any difference. And that [[
operator that seems to be problematic here looks standard, though I don't know what the difference is between [[ ]]
and [ ]
, which both correspond to testing the expression, as far as I know. I'm using Debian squeeze with bash
$ bash --version
GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)
Debian says version 4.1-3
.
ls -al $(which sh)
to see if yoursh
command is what you think it is. :-)[[
is non-standard and makes a script non-portable