2

$values contains a string which I grep from a config file. This string can be eiter: ?, ! or just a string containing words like "foo bar".

values="?"
for value in ${values}
do
    echo "value is ${value}"
done

If I execute the script on local host, the result is:

value is ?

However, if i execute the script from a remote host (using ssh and sudo su - someuser "/tmp/foo.sh"), the result is:

value is 2

Until now, I was not able to find out whats different. Could anyone help please?

3
  • I'm guessig that the variable is expanded for some reason. Maybe the other side default shell is not bash? What does 'echo $0' output? Commented Dec 17, 2013 at 10:18
  • Whether arguments are expanded or not can depend on whether there is a match in the target directory. I have a script x.sh that echos all its arguments. ./x.sh ?.sh echos 'x.sh' while ./x.sh ?.sl echos '?.sl' because there is no match. Commented Dec 17, 2013 at 10:29
  • Do you have any file called 2 in your remote machine? Note that ls ? returns 2 if you happen to have a file with that name, or -in general- it returns the list of files with one character name. Commented Dec 17, 2013 at 10:30

1 Answer 1

3

You need to quote variables, otherwise bash will try to expand $values in the for-header.

values="?"
for value in "${values}"
do
    echo "value is ${value}"
done

? by itself in bash tries to expand to any single character file names in the current directory. e.g.

$ mkdir somedir
$ cd somedir
$ echo ?
?
$ mkdir a
$ echo ?
a 
$ touch {b..z}
$ echo ? 
a b c d e f g h i j k l m n o p q r s t u v w x y z

So depends on what you have on each system, guessing you have a file 2 on the remote host.

Sign up to request clarification or add additional context in comments.

3 Comments

Another option is to set noglob. Read more here
Noglob works. But I dont understand why the shell does not expand the ? character when starting the script locally, but it is expanded if I start the script from a different host.
@Phil I'm positive it does expand the character locally, very likely you just don't have any single character files in the directory on your local computer. And default behavior for special characters when that happens is just to display the special character. For example go to an empty directory and echo * and it will actually print *.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.