passing asterisk to a script as variable

I'm writing a script that will ssh to a number of hosts and run commands. I'm a bit stumped at the moment as some of the commands that I need to run contain wildcards (i.e. *), and so far I have not figured out how to escape the * character so the script doesn't expand it. More specifically, here's an excerpt of the script.

Let's say I'm trying to pass a command some_command * options to the script. No matter how I tried escaping the *, $@ variable always converts it to the list of files. Any ideas on how to fix this?

some_command '*' options

No go... already tried that. * is still expanded into the list of files in current directory. Backslash doesn't work, either.

Quote the variables. It is not $@ that expands the asterisk, but the shell that called the script.

You will also have to escape the asterisk:

[CODE]
COMMAND="whatever \* whatever"
ssh "$HOST" "$COMMAND"
{/CODE]

Nope, still doesn't work... I tried that one as well. It doesn't expand the file list anymore, but then I have the backslash as part of my variable (see below for an example).

I'm not sure it's the shell that's expanding the variable:

$ echo "some_command \* options"
some_command \* options
$ echo "some_command * options"
some_command * options

meanwhile, by adding "echo $COMMAND" to my script, I get:

./test-script "some_command * options"
some_command ...list of files... options

./test-script "some_command \* options"
some_command \* options

I tried running the script from bash and ksh with the same results.

The shell is the only thing that does expand wildcards, unless you have written something else to do it.

The wildcard will not be expanded if it is quoted.

Always quote your variables (unless you have a good reason not to):

ssh "$HOST" "$COMMAND"

As previously stated in an ssh script, the commands ( and eventually all the special characters in them, for example: *, $, ...) will be evaluated first by the current shell, before ssh-in.

So you need to properly escape all of them. For more check these threads:

http://www.unix.com/shell-programming-scripting/48206-how-execute-multiple-commands-via-ssh.html

-

You could parse the command line parameters inside the script.

cat test-script

#!/bin/sh

COMMAND=$(echo "$@" | sed 's/\\//')

for HOST in `cat $INFILE | grep -v ^#`
do
   echo "============== $HOST ==============="
   echo " "
   ssh $HOST $COMMAND
   echo " "
   echo " "
done
test-script "some_command \* options"

That was it, this was the source of the problem! Thanks for pointing it out! :b:

Thanks again for the help, it works fine now that I quote the variable inside the script :slight_smile: