Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 948
Satheesh Avatar asked May 07 '15 16:05

Satheesh


People also ask

What does {} mean in bash script?

{} has absolutely no meaning to bash , so is passed unmodified as an argument to the command executed, here find . On the other hand, ; has a specific meaning to bash . It is normally used to separate sequential commands when they are on the same command line.

What does {} do in Linux?

Within the -exec stuff an argument of {} means "insert the file name here". So if the files were "foo" and "bar" it would execute "ls -a foo" then "ls -a bar".

What is the purpose of {} squiggly braces in Java?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

What does curly brackets mean in shell script?

The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.


2 Answers

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.

like image 146
Cloud Avatar answered Oct 30 '22 18:10

Cloud


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

like image 26
Vic Avatar answered Oct 30 '22 17:10

Vic