10

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?

14

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)
  • 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 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 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.