what is +$ in this command: [[ $1 =~ ^[0-9]+$ ]]
2
The + applies to the [0-9] and not the $.
+
[0-9]
$
The intended command was:
[[ $1 =~ ^[0-9]+$ ]]
It checks if $1 only contains digits, e.g. 123 or 9 (but not 123f or foo or empty string).
$1
123
9
123f
foo
It breaks down as:
[[
=~
^[0-9]+$
^
[0-9]+
]]
+ in regexp matches for “1 or more times the preceding pattern” and $ signifies the end of string anchor.
^ is beginning of string anchor (the natural complement to $), and [0-9] matches any single digit (in the range of 0 to 9).
Click here to cancel reply.
2
Answers
The
+
applies to the[0-9]
and not the$
.The intended command was:
It checks if
$1
only contains digits, e.g.123
or9
(but not123f
orfoo
or empty string).It breaks down as:
[[
, start of a Bash extended test command$1
, the first parameter=~
, the Bash extended test command regex match operator^[0-9]+$
, the regex to match against:^
, anchor matching the start of the line[0-9]+
, one or more digits[0-9]
, a digit+
, one or more of the preceding atom$
, anchor matching the end of the line]]
to terminate the test command+
in regexp matches for “1 or more times the preceding pattern” and$
signifies the end of string anchor.^
is beginning of string anchor (the natural complement to$
), and[0-9]
matches any single digit (in the range of 0 to 9).