您的位置:首页 > 运维架构 > Shell

shell script里面的美元符号什么时候该用

2012-08-14 11:01 477 查看


Shell Script

#!/bin/sh
foo=Hello
echo $foo World


This will say “Hello World”. But did you see what happened with the dollars? To set a variable, no dollar. To read it, use the dollar.

This is particularly confusing to many users of the shell. I can’t even provide a good reason as to why it should work this way, whether historically or pragmatically.

Similarly, when reading variable contents, do not use the dollar:
#!/bin/sh
echo "What do you want to tell the world?"
read msg
echo $msg World


This will tell your message to the world… if you say “Hello”, then it will say “Hello World”. If you say “Goodbye Cruel”, then it will say “Goodbye Cruel World”.

Notice the dollars… whilst strange, it is at least consistent. You use the dollar symbol to quote the content of the variable; otherwise, leave it out.

For more in-depth stuff about variables, check out http://steve-parker.org/sh/variables1.shtml, http://steve-parker.org/sh/variables2.shtml
and http://steve-parker.org/sh/variables3.shtml.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: