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"
fibash 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
MediumWrite a script that sorts git branch names into kinds.
- Open
branch.sh. It takes one branch name as its first argument. - If the name is empty, print
No branch name. - If the name is
mainormaster, printNAME is protected. - If the name starts with
feature/, printNAME is a feature branch. - For any other name, print
NAME is another branch. - Use
[[ ]]for every test, then save the file.
Try it: run bash branch.sh feature/login. It prints:
feature/login is a feature branchThen run bash branch.sh with no name: it prints No branch name.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground