Skip to content

Bash

Example

index: shebang

#!/usr/bin/env bash

foo="World"
echo "Hello $foo!"

Conditions

STRING="foo"
if [[ -z "$STRING" ]]; then
    echo "Empty string"
elif [[ -n "$STRING" ]]; then
    echo "Not empty string"
elif [[ "$STRING" == "$STRING" ]]; then
    echo "Equal"
elif [[ "$STRING" != "$STRING" ]]; then
    echo "Not Equal"
elif [[ "$STRING" =~ ^f.* ]]; then
    echo "Regexp"
else
    echo "Else"
fi

NUM=1
if [[ NUM -eq NUM ]]; then
    echo "Equal"
elif [[ NUM -ne NUM ]]; then
    echo "Not equal"
elif [[ NUM -lt NUM ]]; then
    echo "Less than"
elif [[ NUM -le NUM ]]; then
    echo "Less than or equal"
elif [[ NUM -gt NUM ]]; then
    echo "Greater than"
elif [[ NUM -ge NUM ]]; then
    echo "Greater than or equal"
elif (( NUM < NUM )); then
    echo "Numeric conditions"
fi

FILE=dir/foo/afile
FILE1=dir/foo/afile1
FILE2=dir/foo/afile2
if [[ -e FILE ]]; then
    echo "Exists"
elif [[ -r FILE ]]; then
    echo "Readable"
elif [[ -h FILE ]]; then
    echo "Symlink"
elif [[ -d FILE ]]; then
    echo "Directory"
elif [[ -w FILE ]]; then
    echo "Writable"
elif [[ -s FILE ]]; then
    echo "Size is > 0 bytes"
elif [[ -f FILE ]]; then
    echo "File"
elif [[ -x FILE ]]; then
    echo "Executable"
elif [[ FILE1 -nt FILE2 ]]; then
    echo "1 is more recent than 2"
elif [[ FILE1 -ot FILE2 ]]; then
    echo "2 is more recent than 1"
else
    echo "Same files"
fi

Functions

function my_func {
    echo "Hello $1"
}

my_func "John"