informatique:outils:bash

Ceci est une ancienne révision du document !


Bash

  • déclaration : array=( 1 2 3 )
  • ajouter un élément : array+=( 4 )
  • lister tous les éléments : echo “${array[@]}”
  • récupérer le nombre d'élement : echo ${#array[@]}

in_array

function in_array() {
    local needle=$1 el
    shift
    for el in "$@"; do
        [ "$el" = "$needle" ] && return 0
    done
    return 1
}

Utilisation :

array=(1 2 3)
in_array 1 ${array[@]} && echo IN
in_array 5 ${array[@]} && echo OUT

implode

function implode() {
  local d=${1-} f=${2-}
  if shift 2; then
    printf %s "$f" "${@/#/$d}"
  fi
}

Utilisation :

array=(1 2 3)
echo $( implode "," "${array[@]}" )
# Output: 1,2,3
echo -e "- $( implode "\n- " "${array[@]}" )"
# Output:
# - 1
# - 2
# - 3
  • informatique/outils/bash.1710939399.txt.gz
  • Dernière modification : 2024/03/20 12:56
  • de bn8