I believe your remaining problem is that $( ... )
and $(( ... ))
are two very different things. The former does command substitution, which is what you want. The latter does arithmetic. Try this:
#! /bin/sh
x=$(grep -c '^[a-z]' "$1")
echo "$x"
I also don't know why you had the caret outside the single quotes; that could cause problems with some shells (where caret either does history expansion or is an alias for |), I think bash is not one of those shells but there's no reason to tempt fate.
Obligatory tangential advice: When expanding shell variables, ALWAYS put them inside double quotes, unless you specifically need word splitting to happen. (This is why I changed $1
to "$1"
. Without that change, your script would break if you gave it a file with a space in its name.)
EDIT: Now you say you want to know if a word passed to a script starts with a number. By "passed to a script" I am going to assume you mean like this:
./script WORD
The easiest way to do that does not involve grep
or command substitution at all:
#! /bin/sh
case "$1" in
[0-9]*)
echo "Starts with a number"
;;
*)
echo "Doesn't start with a number"
;;
esac
Yes, the "case" syntax is gratuitously different from everything else in shell; if you want an internally consistent language, Python is waiting for you thataway. The patterns you put before each open paren are globs, not regexes. If you need a regex, you have to do something more complicated, e.g.
#! /bin/sh
if [ $(expr "$1" : '^[0-9]\{3,5\}x') -gt 0 ]; then
echo "Starts with a three-to-five digit number followed by an x"
fi
Some people say that it is unnecessary to put quotes around the variable expansion that goes between case
and in
. They are technically correct but should be ignored anyway, because that's one too many warts to remember. Other people say that you can put an open parenthesis before each glob and then your editor will not get grumpy about the mismatched parentheses. I approve of editor non-grumpiness, but I don't know how portable that variation is.