45

For a fixed prefix length I can do it like so:

[ a${filename:0:2} = a.# ] && echo temporary emacs file

How to do it for an arbitrary prefix?

Is there a cleaner way?

thomas
  • 453
  • 1
  • 4
  • 4
  • 1
    possible duplicate of [In bash, how can I check if a string begins with some value?](http://stackoverflow.com/questions/2172352/in-bash-how-can-i-check-if-a-string-begins-with-some-value) – tripleee Sep 06 '13 at 07:14

2 Answers2

60

[['s = operator takes a pattern in the right operand.

var=123
[[ 1234 = $var* ]] && ...
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Do you mean `[[ ${var_to_test}a = ${prefix}*a ]] && ...`? – thomas Nov 09 '10 at 10:33
  • 4
    You don't need the `a` at the end; `[[` does not have the same limitations as `test`. – Ignacio Vazquez-Abrams Nov 09 '10 at 10:34
  • You're right. If there is a variable on the left hand side even if it empty the expression still works (I was confused due to I've tested it in the shell without any name on the lhs, so it'd produced syntax errors; but in a script there always will be some variable name.) – thomas Nov 09 '10 at 10:41
30

Here the 'regex' version (2015, bash 3.x and newer) of Ignacio's answer, using operator =~:

[[ "1234" =~ ^12 ]] && echo y

If you need a dynamic prefix from a variable:

var=12
[[ "1234" =~ ^$var ]] && echo y

When using complex regular expressions you can place them in a own variable:

var=12
var2=a
regex="^${var}.+${var2}.+$"
[[ "1234a567" =~ $regex ]] && echo y

See also the 'Conditional Constructs' section of the Bash man page on command [[:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

t0r0X
  • 4,212
  • 1
  • 38
  • 34