Difference between braces {} and brackets () in shell scripting

痴心易碎 提交于 2019-12-05 22:37:02

问题


We use braces {} for variable expression like

NAME="test"

FILE_NAME=${NAME}file

But I don't understand in which scenarios we use brackets () Say nslookup $(hostname) works only with () brackets.

Can someone explain?


回答1:


Minor nitpick first:

  • Brackets []
  • Parentheses ()
  • Braces {}
  • (Double) Quotation marks ""
  • (Single) Quotation marks (apostrophes) ''
  • Backticks `` (Same as the tilde ~ key)

Braces are used in BASh scripts for complex variable expansion. Consider string concatenation:

STR="hello"
STR2=$STR

STR2 evaluates to "hello". What if you wanted to make it something like "helloWorld". Doing something like STR2="$STR2World" won't work, so you use braces, ie: STR2="${STR}World".

As for brackets, they are used, similar to the backtick, `, which expands the text between them as the text output from a command.

What if you wanted to store the current time as a string?

STR2=$(date)

Now STR2 stores the string "Thu May 7 09:32:06 PDT 2015".

Additionally, you can use parentheses to execute something in a subshell, which will potentially affect your environment, PID, etc. Very useful for cases where you want a "throwaway" environment with having to track/restore environment variables, directories via pushd/popd instead of cd, etc.




回答2:


Using parentheses ( executes something. There happens to be a program named hostname - so $(hostname) will execute it.

try which hostname to see where that program resides



来源:https://stackoverflow.com/questions/30106758/difference-between-braces-and-brackets-in-shell-scripting

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