bash 初始化变量的不同方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8554791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Different ways to initialize a variable
提问by Paul Manta
As far as I've seen there are two ways to initialize a variable with the output of a process. Is there any difference between these two?
据我所知,有两种方法可以用进程的输出初始化变量。这两者有什么区别吗?
ex1=`echo 'hello world'`
ex2=$(echo 'hello world')
回答by Micha? ?rajer
You get same effect.
你得到同样的效果。
The $()is recommended since it's more readable and makes it easier to nest one $()into another $().
该$()建议,因为它是更具可读性和更容易窝一个$()到另一个$()。
Update:
更新:
The $()syntax is a POSIX 1003.1 standard (2004 edition). However, on some older UNIX systems (SunOS, HP-UX, etc.) the /bin/shdoes not understand it.
该$()语法是POSIX 1003.1标准(2004年版)。但是,在一些较旧的 UNIX 系统(SunOS、HP-UX 等)上,/bin/sh它不理解。
You might need to use backtick "`" instead or use another shell (usually it's ksh) if you need your script to work on such environment.
如果您需要您的脚本在这样的环境中工作,您可能需要使用反引号 "`" 或使用另一个 shell(通常是 ksh)。
If you don't know which syntax to use - use $(). Backtick syntax is deprecated.
如果您不知道使用哪种语法 - 使用$(). 不推荐使用反引号语法。
回答by Samus_
see http://mywiki.wooledge.org/BashFAQ/082
见http://mywiki.wooledge.org/BashFAQ/082
also notice that $()is POSIX so it does work on sh.
还请注意,这$()是 POSIX,因此它确实适用于 sh。
回答by jaypal singh
There is another way to initialize a variable to a default one if you haven't initialized it yourself.
如果您自己没有初始化变量,还有另一种方法可以将变量初始化为默认变量。
[jaypal:~/Temp] a="I have initialized var a"
[jaypal:~/Temp] echo ${a:="Default value"}
I have initialized var a
[jaypal:~/Temp] a=
[jaypal:~/Temp] echo ${a:="Default value"}
Default value

