23

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?

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Mattias
  • 1,527
  • 3
  • 13
  • 14

1 Answers1

29

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)
jimmij
  • 46,064
  • 19
  • 123
  • 136
  • 1
    Right, I actually didn't think of that. But so `var=(1 2 3); echo $var` is the same as `var=(1 2 3); echo ${var[0]}`? – Mattias Jul 23 '15 at 13:36
  • Yes, the result in `bash` is the same. – jimmij Jul 23 '15 at 13:38
  • Do we need `""` in `echo "${a}"`? – nn0p Feb 10 '19 at 14:42
  • @nn0p Yes we do, if we don't want to perform split and glob operation on `a`. Consider for example `a=*`, then try `echo $a` and `echo "$a"`. – jimmij Feb 10 '19 at 14:52
  • I expounded upon your answer to make your array example more complete, by adding some bash array slicing examples to it in the bottom of my answer here: [Bash: slice of positional parameters](https://unix.stackexchange.com/a/664956/114401). – Gabriel Staples Aug 16 '21 at 21:25