Use Double Brackets Instead Of Single Bracket For Tests In Bash

  • historically, before any conditional expressions, there was an only command called test
  • test is still there for compatibility with other sh shells
  • test is also known as [ — single square bracket instead of two square bracket
  • you can encounter [ in the wild also in bash scripts a lot
  • [ is a regular shell command
  • therefore there are lots of tiny pitfalls for the old test command or [
  • beware that [ exists but don't use it
  • rule: use [ only if you need a script that has to run on non-bash shell machines
  • Make sure you have the #!/bin/bash shebang line for your script if you use double brackets.
  • [[ originates from bash and is generally treated as bash-specific (don't know about other shells there may be adoption)
  • [[ is easier
  • [[ is not a command
  • [[ is a bash extension
  • it has a dedicated syntax and it is parsed in a special way
  • e.g. no need to quote variables
  • write help test to get info on essentials
  • write help [[ for bash specific operations
  • from my experience, however, I keep seeing [ also in bash-only scripts so the the knowledge of differences is still relevant

1. logical operators

  • can use && and || operators for boolean tests
  • can use < and > for string comparisons.
  • [ cannot do this because it is a regular command
  • &&, ||, <, and > are not passed to regular commands as command-line arguments

2. regex

  • can use =~ operator for regex matches
  • capture groups are stored in BASH_REMATCH var
if [[ $answer =~ ^y(es)?$ ]]

3. globbing

  • can use pattern matching with wildcards
if [[ $ANSWER = y* ]]

links

--

--

--

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Announcing DevBlog Launch & Website Updates

Difference between Algorithms and Pseudocode

Strange git-things happens

Build the next big thing at the ZK Hackathon!

How to build a serverless Laravel queue using AWS Lambda

How A Runaway Thief Shut Down Amsterdam’s Train Traffic By Exposing A Simple Software Bug

This Week In TurtleCoin (Jan 1, 2019)

CRO partnering with Veeva eTMF

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

Getting the Terminal Width in C

What happens behind when you compile a C file?

GCC logo (GNU Compiler Collection)

Print Works As Return Statement When Fetching Values In Bash From Python Scripts

How Secure is Your Linux PC ?