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

x
  • 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!
0
beer9
Asked:
beer9
2 Solutions
 
TintinCommented:
Hopefully the following example makes it clearer

#!/bin/bash
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
test2
test3

Open in new window


Short answer is that you should use quotes around variables when you use [, but is not needed when you use [[
0
 
farzanjCommented:
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 [ ].
0

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