Ceci est une ancienne révision du document !


Bash

:!: le shell par défaut à la création du compte est /bin/bash. Vous pouvez demander à en changer via les formulaires web.

Utilisez shellcheck !!

Exemples & Astuces

pattern matching

#! /bin/bash
 
VARIABLE="Let's test this string!"
 
# This is for regular expressions:
if [[ "$VARIABLE" =~ "Let's.*ring" ]]
then
    echo "matched"
else
    echo "nope"
fi
 
# And here we have Bash Patterns:
if [[ "$VARIABLE" == L*ing! ]]
then
    echo "matched"
else
    echo "nope"
fi
#! /bin/bash
 
VARIABLE="Let's test this string!"
 
# This is for regular expressions:
if [[ "$VARIABLE" =~ "Let's.*ring" ]]
then
    echo "#1 matched"
else
    echo "#1 nope"
fi
 
if [[ "$VARIABLE" =~ Let\'s.*ring ]]
then
    echo "#2 matched"
else
    echo "#2 nope"
fi

Results: #1 nope #2 matched

To get #1 matching remove quotes around RegExpr or set compat31 : shopt -s compat31

#!/bin/sh
 
thisString="1 2 3 4 5"
searchString="1 2"
# if you single quote your input, you could do this
# searchString=$1
 
case $thisString in
  # match exact string
  "$searchString") echo yep, it matches exactly;;
 
  # match start of string
  "$searchString"*) echo yep, it matches at the start ;;
 
  # match end of string
  *"$searchString") echo yep, it matches at the end ;;
 
  # searchString can be anywhere in thisString
  *"$searchString"*) echo yep, it matches in the middle somewhere ;;
 
  *) echo nope ;;
esac

Tableaux associatifs

On peut nommer les entrées d'un tableau (l'index).

  • astuce :
tab[wwsi]="whatever/wwsi"
tab[wwoz]="whatever/to/wwoz"
tab[fip]="http://audio.scdn.arkena.com/11016/fip-midfi128.mp3"

Lister le tableau associatif :

  • brute :
for i in "${tab[@]}"; do echo "${i}"; done
  • astuce (boucle induite) :
printf "%s\n" "${tab[@]}"; done

Simplification de code résultante :

Parcours du tableau, connaissant l'index (ici $value).

  • Avant :
tindex=$(for i in "${tab[@]}"; do echo "${i}"; done | grep "${value}")
for ((i=0; i<${#tab[@]}; i++))
do
  if [[ "$tindex" == "{tab[$i]}" ]]
  then
    data="${tab[$i]}"
  fi
done
  • Aprés :
tindex=$(printf "%s\n" "${tab[@]}" | grep "${value}")
data="${tab[$tindex]}"
Tout ces exemples de scripts bash n'ont pas forcément été testé avec shellcheck. Faites-le !
documentation/tools/langages/bash.1673599654.txt.gz · Dernière modification : 2023/01/13 08:47 de ltaulell