Bash – Single Parenthesis in Variable Assignment

arraybash

I was wondering about single parentheses in bash. I know that they are used for executing commands in subshells and that they are used for creating arrays, but are they used for anything else?

One thing that caught my attention is that when you use the in variable assignment, like

var=(hello)
echo $var    # hello

bash doesn't generate an error or anything, and the output is the same as if

var=hello

Are these two variable definitions the same or is there a difference?

Best Answer

In your case parenthesis () are used as array definition, for example

a=(one two three)   # array definition
echo "${a}"         # print first element of array a
echo "${a[0]}"      # print first element of array a
echo "${a[1]}"      # print *second* element of array a
echo "${#a[@]}"     # print number of elements in array a

If you put single variable in array then you just have an array with single element.


To answer your other question whether parenthesis are also used for anything else: there are many situations in bash that in combination with other characters they can be used as:

  • command substitution: $()
  • process substitution: <() and >()
  • subshell: (command)
  • arithmetic evaluation: (())
  • function definition: fun () { echo x; }
  • pattern list in glob: ?(), *(), +(), @(), !() (only if extglob is enable)
Related Question