Bash

Variables

Tester l'existence d'une variable

[ -z ${var+x} ] && echo 'Var is unset'

Test l'existance d'un programme

if ! command -v <the_command> 2>&1 >/dev/null
then
    echo "<the_command> could not be found"
    exit 1
fi

Mail

Envoyer un mail avec sendmail

sendmail "adress1@domain.ltd,address2@domain.ltd" -s "smtp.domain.ltd" <<- EndOfMail
    Subject: This is the subject
    From: test@domain.ltd
    Content-Type: text/plain; charset="utf8"

    Hello world !
EndOfMail

Tableaux

Déclaration

declare -A ARRAY
ARRAY[0]="foo"
ARRAY[1]="bar"

Boucle sur un tableau

for item in "${ARRAY[@]}"; do
  [...do something whith $item...]
done

Divers

Gérer les arguments de commande

options=$(getopt -o c:hp:s: -l hide-pagination,page-count:,page-size:,sort:,help -- "$@")
eval set -- "$options"
while true; do
  case "$1" in
    -c|--page-count)
      PAGE_COUNT=$2
      shift 2
      ;;
    -h|--hide-pagination)
      HIDE_PAGES=1
      shift
      ;;
    -p|--page-size)
      PAGE_SIZE=$2
      shift 2
      ;;
    -s|--sort)
      SORT="$2"
      shift 2
      ;;
    --help)
      show_help
      exit
      ;;
    --)
      shift
      break
      ;;
  esac
done

REPO="$1"
shift

Récupérer le chemin du répertoire du script en cours d'exécution

CD="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

Lire les vidéos d'un répertoire en boucle

#!/bin/bash

DIR="videos"
PLAY="omxplayer -o hdmi"

DIR="$(dirname "$0")/$DIR"

if [[ $(find $DIR -type f | wc -l) == 1 ]]; then
        $PLAY --loop $DIR/*
else
        while true; do
                for file in $DIR/*; do
                        $PLAY $file
                done
        done
fi