问题
$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?
回答1:
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.
来源:https://stackoverflow.com/questions/20631316/bash-shell-for-loop-returns-different-values