I'm going through my bash book and came across this if statment.
if [ -n "$(echo $1|grep '^-[0-9][0-9]*$)" ]; then
the book says that the grep expression means "an initial dash followed by a digit" (which I understand) "optionally followed by one or more digits" That's the part I can't figure out -- I know the * is a wildcard symbol, but the $ I'm only familiar with in displaying the values of variables and the like, so how do these symbols mean what they do in this expression? If you could break it down for me I'd really appreciate it. Do these symbols have another meaning that I'm not aware of?
It probably is supposed to mean "if $1 is a negative number, then", but a single quote is missing after the $ sign
It is equivalent to this:
if [ $1 -lt 0 ]; then
or this if $1 may contain values other than a number
if [ $1 -lt 0 ] 2>/dev/null; then
$1 is the 1st positional parameter passed to your script.
actuall I did forget the single quote, but it isn't referring to a negative number. It's part of a sample script. I should have included the whole thing.
if [ -n "$(echo $1 | grep '^-[0-9][0-9]*$')" ]; then
howmany=$1
shift
elif [ -n "$(echo $1 | grep '^-')" ] ;then
print 'usage: highest [-N] filename'
exit 1
else
howmany="-10"
fi
filename=$1
sort -nr $filename |head $howmany
what I wanted to know was how the * and $ mean what my book says it means, because I don't see it (particularly the dollar sign at the end of the grep expression; I know what it means in reference to the positional parameter).
$ marks the end of a line (or string) if used at the end of a regular expression (match-end-of-line operator).
- means zero or more occurrences of the preceding character (repetition operator), in this case a digit ([0-9])
Maybe this can bring some lights in the dark too:
POSITIONAL PARAMETER REFERENCE
So just to be clear, the grep expression means "look at the first positional prameter and see if it begins with a -. If it does, then see if it's followed by a digit from 0 to 9. If that's the case, then see if there are or not any other digits after it until the end of the line, with no letters or symbols in between" ?
Also, am I correct in assuming that these symbols have these charateristics only in a grep expression?
Correct. These symbols have this meaning in regular expressions (regex).