Menu
CoddyTech

Double Brackets

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 6 of 39.

[[ ]] is bash's own test. It does what [ ] does and adds string tools. == is true when two strings match and != when they do not. An unquoted right side is a glob pattern, where * stands for any characters, so *.png matches every name ending in .png. -z is true for an empty string and -n for a non-empty one. Inside [[ ]], && means both and || means either.

#!/bin/bash
f=$1
if [[ -z $f ]]; then
  echo "No file given"
elif [[ $f == *.jpg || $f == *.png ]]; then
  echo "$f is an image"
else
  echo "$f is not an image"
fi

bash kind.sh cat.png prints cat.png is an image, and bash kind.sh prints No file given. A variable inside [[ ]] needs no quotes, even when it holds spaces. Quote the pattern and it becomes plain text: [[ $f == "*.png" ]] only matches a name that is literally *.png.

challenge icon

Challenge

Medium

Write a script that sorts git branch names into kinds.

  1. Open branch.sh. It takes one branch name as its first argument.
  2. If the name is empty, print No branch name.
  3. If the name is main or master, print NAME is protected.
  4. If the name starts with feature/, print NAME is a feature branch.
  5. For any other name, print NAME is another branch.
  6. Use [[ ]] for every test, then save the file.

Try it: run bash branch.sh feature/login. It prints:

feature/login is a feature branch

Then run bash branch.sh with no name: it prints No branch name.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground