typestar

if & [[ ]] in Bash

Branching on comparisons, globs and the filesystem.

count=7
name="typestar"

# [[ ]] is bash's test: safer than [ ], no quoting surprises
if [[ $count -gt 5 ]]; then
    echo "count is high"
fi

if [[ $name == type* ]]; then
    echo "glob match inside [[ ]]"
fi

# file tests: -f exists, -d directory, -s non-empty
if [[ -d /tmp && ! -f /no/such/file ]]; then
    echo "filesystem looks sane"
fi

How it works

  1. [[ ]] is the modern test: no quoting surprises inside.
  2. -gt compares numbers; == with a glob matches patterns.
  3. -f, -d and friends ask the filesystem directly.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
332
Tokens
51
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 36 seconds.

Type this snippet

Step 1 of 3 in Conditionals, step 4 of 26 in Language basics.

← Previous Next →