tags:

views:

134

answers:

2

How do I include a string with an expression in a command in a bash script?

Consider the following:

#!/bin/bash
exclusions='Database|information_schema|mysql'
echo "mysql -e 'SHOW DATABASES' | grep -E -v '$exclusions' > outfile"
mysql -e 'SHOW DATABASES' | grep -E -v '$exclusions' > outfile

The script prints to the screen:

mysql -e 'SHOW DATABASES' | grep -E -v 'Database|information_schema|mysql' > outfile

... so I think my syntax is producing the command string I want. And when I manually enter the printed string at the command line, the command puts all database names, except those in the grep expression, into 'outfile'.

But the script exports all database names, without excluding those in the grep expression, to the file. Why is the script overlooking the grep expression?

+3  A: 

Environment variables (and other special characters) are not expanded inside single-quoted strings. The one in the echo statement is, because the string itself is delimited by the double quotes. The single quotes in that string are part of the string, not the delimiters.

See the what the bash manual says about quoting.

Nick Meyer
+2  A: 

Use double quotes instead of single quotes.

mysql -e 'SHOW DATABASES' | grep -E -v "$exclusions" > outfile
Dave Hinton