views:

184

answers:

3

How do I write a shell script (bash on HPUX) that receives a string as an argument containing an asterisk?

e.g. myscript my_db_name "SELECT * FROM table;"

The asterisk gets expanded to all the file names in the current directory, also if I assign a variable like this.

DB_QUERY="$2"
echo $DB_QUERY
+2  A: 

You always need to put double quotes around a variable reference if you want to prevent it from triggering filename expansion. So, in your example, use:

DB_QUERY="$2"
echo "$DB_QUERY"
Nicholas Riley
+2  A: 

The asterisk "*" is not the only character you have to watch out for, there's lots of other shell meta-charaters that can cause problems, like < > $ | ; &

The simple answer is always to put your arguments in quotes (that's the double-quote, " ) when you don't know what they might contain.

For your example, you should write:

DB_QUERY="$2"
echo "$DB_QUERY"

It starts getting awkward when you want your argument to be used as multiple parameters or you start using eval, but you can ask about that separately.

Adrian Pronk
A: 

In the first example, use single quotes:

myscript my_db_name 'SELECT * FROM table;'

In the second example, use double quotes:

echo "$DB_QUERY"
William Pursell