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

is_empty

function is_empty() {
        [ $# -gt 0 ] && return 1
        return 0
}

Utilisation :

array=(1 2 3)
is_empty $array && echo empty
! is_empty $array && echo not empty

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
#!/bin/bash
 
DEBUG=0
BIN_PATH="/bin/binary"
EXTRA_ARGS=()
 
function usage() {
        error="$1"
        [ -n "$error" ] && echo "$error"
        cat << EOF
Usage : $(basename $0) [-d] [-b /path/to/binary]
        -b [path]               Binary path (default: $ENGINE)
        -d                      Debug mode
        -X                      Enable bash tracing (=set -x)
        -h                      Show this message
EOF
        [ -n "$error" ] && exit 1
        exit 0
}
 
function debug() {
        [ $DEBUG -eq 1 ] && >&2 echo -e "$( date '+%Y-%m-%d %H:%M:%S' ) - $@"
}
 
idx=1
while [ $idx -le $# ]
do
        OPT=${!idx}
        case $OPT in
                -d)
                        DEBUG=1
                ;;
                -h)
                        usage
                ;;
                -b)
                        ((idx++))
                        BIN_PATH=${!idx}
                        if [ ! -x "$BIN_PATH" ]
                        then
                                usage "Invalid binary path ($BIN_PATH)"
                        fi
                ;;
                -X)
                        set -x
                ;;
                *)
                        EXTRA_ARGS+=( $OPT )
                ;;
        esac
        ((idx++))
done
 
debug "Extra args: ${EXTRA_ARGS[@]}"
  • informatique/outils/bash.1710956163.txt.gz
  • Dernière modification : 2024/03/20 17:36
  • de bn8