Bash Shell: for loop returns different values

☆樱花仙子☆ 提交于 2020-01-15 03:26:16

问题


$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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!