Vaughn
Vaughn

Reputation: 396

grep: character class syntax is [[:space:]], not [:space:]

I'm trying to get list of all the databases on my server which I'll use to backup. Following is a snippet of code which I'm trying to print the list of databases but I get error. How to fix it? Adding double square brackets doesn't solve it.

I've looked into some similar questions but I can't figure out.

grep: character class syntax is [[:space:]], not [:space:]

#!/bin/sh -

IFS='
        '
OLDPATH="$PATH"

PATH=/sbin:/bin:/usr/bin
export PATH

MUSER=root
MPASS='sfdsfdf'

DBLIST=$(mysql -u${MUSER} -p${MPASS} -e 'show databases;' |  grep [:alphnum:] | grep -v Database)
for base in ${DBLIST}; do
    echo $base
done

Upvotes: 3

Views: 4100

Answers (1)

jhnc
jhnc

Reputation: 16829

The line producing the error is:

DBLIST=$(mysql -u${MUSER} -p${MPASS} -e 'show databases;' |\
grep [:alphnum:] | grep -v Database)

When the first grep is run, it notices that there is a pair of brackets containing text between colons. It guesses that the user intended to put a character class inside a bracket expression and gives an example of the correct way to do this.

A bracket expression is written [list of characters].

A character class is written: [:class:] for some value of class.

A character class (eg. [:space:]) is used by placing it inside a bracket expression, along with any other characters to be matched. So to match whitespace and the digits one through three, one could write: [[:space:]123]

Unfortunately, there is another error in the code, which is that there is no such character class as "alphnum". So correcting the bracketing doesn't help!

There is however a class: [:alnum:]

If this is the class intended, the first grep should be amended to:

grep [[:alnum:]]

Note that brackets are treated specially by the shell (they can expand into filenames) so it is safer to quote any occurrences:

grep '[[:alnum:]]'

Upvotes: 8

Related Questions