Bash programming

File header

#!/bin/bash

CLI param

echo $1
echo $2
# cli param1 param2

Check param is (not) empty

if [ -z "$1" ]; then
    echo "empty param"
fi

if [ ! -z "$1" ]; then
    echo "not empty param"
fi

Bash Equals-Separated (e.g., –option=argument) (without getopt[s]) 1

#!/bin/bash

for i in "$@"
do
case $i in
    -e=*|--extension=*)
    EXTENSION="${i#*=}"
    shift # past argument=value
    ;;
    -s=*|--searchpath=*)
    SEARCHPATH="${i#*=}"
    shift # past argument=value
    ;;
    -l=*|--lib=*)
    LIBPATH="${i#*=}"
    shift # past argument=value
    ;;
    --default)
    DEFAULT=YES
    shift # past argument with no value
    ;;
    *)
          # unknown option
    ;;
esac
done
echo "FILE EXTENSION  = ${EXTENSION}"
echo "SEARCH PATH     = ${SEARCHPATH}"
echo "LIBRARY PATH    = ${LIBPATH}"
echo "DEFAULT         = ${DEFAULT}"

Varable

Put value to dynamiclly varable

A_VAR='a'
eval "$1_VAR"='cc'
echo $A_VAR

reference a file for variables 2

source FILE
# or
. FILE

Path

Source path

Dirname

$(dirname "$0")

Source path

SOURCE="${BASH_SOURCE[0]}"
echo $SOURCE

Source directory path 3

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

Execution directory

echo $(pwd)

File and directory

Getting the contents of a directory using shell script. 4

for entry in "$search_dir"/*
do
  echo "$entry"
done

Check directory

if [ -d "$DIR" ]; then
    exit 0
else
	exit 1
fi

Conditionals 5

Bash Operator Operator Description
-eq == Equal
-ne != Not equal
-gt > Greater than
-ge >= Greater than or equal
-lt < Less than
-le <= Less than or equal
-z == null Is null

Looping 6

#!/bin/bash

FILES=/Users/tania/dev/*

for file in $FILES
do
    echo $(basename $file)
done

Color

You can use these ANSI escape codes:7

#    .---------- constant part!
#    vvvv vvvv-- the code from above
RED='\033[0;31m'
NC='\033[0m' # No Color
printf "I ${RED}love${NC} Stack Overflow\n"
#!/bin/bash

RED='\033[0;31m'
YELLO='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
echo -e "I ${RED}love${NC} coding"
echo -e "I ${YELLO}love${NC} coding"
echo -e "I ${GREEN}love${NC} coding"
Color Code Color Code
Black 0;30m Dark Gray 1;30m
Red 0;31m Light Red 1;31m
Green 0;32m Light Green 1;32m
Brown/Orange 0;33m Yellow 1;33m
Blue 0;34m Light Blue 1;34m
Purple 0;35m Light Purple 1;35m
Cyan 0;36m Light Cyan 1;36m
Light Gray 0;37m White 1;37m

functions

function get_string()
{
	echo "string"
}

STRING=$(get_string)

Pass params into function 8

function get_string()
{
        echo "$1"
}


STRING=$(get_string aaa)

echo $STRING