[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 266
  • Last Modified:

double quote of variable in test or [ ] or [[ ]]

Hello, I am trying to follow on some bash scripting tutorial and realized that we need to be careful on using a variable with or without double quote in test/[]/[[]] operator. But I am getting some confusion when and where do we use that. Could someone please help me to understand it with example. Thanks!
2 Solutions
Hopefully the following example makes it clearer

foo="some value"
[ $foo = "some value" ] && echo test1
[ "$foo" = "some value" ] && echo test2
[[ $foo = "some value" ]] && echo test3

Open in new window

Output is:

test.sh: line 3: [: too many arguments

Open in new window

Short answer is that you should use quotes around variables when you use [, but is not needed when you use [[
The newer standard is to use [[ ]] in both Bash and Korn.  [ ] is for backward compatibility with Borne shell.

With [[ ]], you can use all the C++ like operator like ==, <=, etc.
With [[ ]], you can use the latest Bash regular expression matching as well.
All the new power of of Bash obtained by using [[ ]].  But some people still want to keep using [ ].

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now