In my script on my ubuntu machine I declare a string like this:

DEBUG_PACKAGE_LIST=$(apt-cache search dbg | awk '{ print $1 }' | grep -e "-dbg")

For you to help you understand my problem here is the output of

echo $DEBUG_PACKAGE_LIST >> debug

The following

if [[ ! $DEBUG_PACKAGE_LIST =~ "[^-a-z0-9]libmagick++5-dbg[a-z]*" ]]; then 
   echo "no contained"; 

echos "not contained", despite $DEBUG_PACKAGE_LIST contains the string "libmagick++5-dbgsym". Could you help me understand why?

Basically my intention is to match libmagick++5-dbg, wheras, libmagick should only be preceeded by a space character.

  • + is an extended regex operator, and some (the recent ones) versions of bash don't treat regexp operators as operators when quoted. – Stéphane Chazelas Aug 1 '14 at 11:18
  • You can also remove a pipe: awk handles pattern matching, awk '/-dbg/ { print $1 }'... – jasonwryan Aug 1 '14 at 21:31

In bash 3.2 or above:

shopt -u compat31
[[ ! $DEBUG_PACKAGE_LIST =~ [^-[:alnum:]]'libmagick++5-dbg' ]];

In bash 3.1:

[[ ! $DEBUG_PACKAGE_LIST =~ '[^-[:alnum:]]libmagick\+\+5-dbg' ]];

(note that [a-z]* is redundant since it also matches the empty string so will always match).

Works in both:

[[ ! $DEBUG_PACKAGE_LIST =~ $re ]]
  • Thanks sir, [^-[:alnum:]] was exactly what I need! Do you have a link to good documentation? BTW: if [[ ! $DEBUG_PACKAGE_LIST =~ [^-[:alnum:]]"libmagick++5-dbg" ]];then echo "not contained";fi works here without problems. I need the quote because libmagick++5 is only an example here, there is an variable $package in my script. – GEO Aug 1 '14 at 11:42

You can't quote the regular expression on the right of such an expression (unless you're using a Bash version >= 3.0-alpha and < 3.2-alpha). If you do, it's treated as a comparison between literal strings.

Also, Bash uses extended regular expressions for =~, where + is a special character.

  • Depends on the version of bash (and on the compat31 option in newer bash versions). – Stéphane Chazelas Aug 1 '14 at 11:20

You can do this with a shell pattern, rather than a regular expression. Prepend a space to the string so that you don't need to treat the first element differently from the others.

if [[ " $DEBUG_PACKAGE_LIST" = *\ libmagick++5-dbg[a-z]* ]]; then 

(Are you sure about the mandatory letter after -dbg? The package name ends with -dbg.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.