Files
linux/docs/shells/bash.md
T

1.9 KiB

Bash

arrays

# creates an array variable
ORPHANS=()

# checks length
if [[ ${#ORPHANS[@]} -eq 0 ]]; then
    echo "No orphans found."
else
    echo "orphans:"
    printf "%s\n" "${ORPHANS[@]}"
fi

associative array

an data structure that lets you store key → value pairs

# clean if already been used
unset PV_PATHS
# declare an associative array, an data structure that lets you store key → value pairs
declare -A PV_PATHS
for name in $(kubectl get pv -o jsonpath='{.items[*].metadata.name}'); do
    path=$(kubectl get pv ${name} -o jsonpath='{.spec.local.path}' 2>/dev/null)
    # check if path is no empty
    [[ -n "${path}" ]] && PV_PATHS["${name}"]="${path}"
done
# print only keys
echo
echo "All Keys:"
printf "%s\n" "${!PV_PATHS[@]}"

echo
echo "All Values:"
# print only values
printf "%s\n" "${PV_PATHS[@]}"

echo
echo "Keys|Values:"
# print all
for key in "${!PV_PATHS[@]}"; do
    printf "%s|%s\n" "$key" "${PV_PATHS[$key]}"
done

misc

#!/bin/bash
script_directory="$(dirname "$(readlink -f "$0")")"
#simbolo para comentário
if <condition>; then
<commands>
fi



if test $variavel -eq 3; then
 echo
fi


if [ $variavel -eq 3 ]; then
 echo
fi

if [ ! $variavel -eq 3 ]; then
 echo
fi

if [ $variavel -eq 3 -a $variavel -eq 2 -o $variavel -eq 1]; then
 echo
fi
``





#!/bin/bash

function echoArguments(){
    echo "printing ($#) arguments"
    for ARGUMENT in "$@"
    do
    echo $ARGUMENT
    done
}
echoArguments $@
Também é possível aceder por índice

#!/bin/bash

function echoArguments(){
   echo "$0"
   echo "$1"
}
echoArguments $@
Testar se um programa está a correr
if pgrep jivelite>/dev/null
 then echo "a correr"
 else echo "nao esta correr"
fi
verifica o numero de parametros
cuidado tem que ter mesmo os espaços nos parenteses rectos

if [ "$#" -ne 2 ]
then
 echo "wrong number of parameters($#)"
 echo "0 - name of processo to search" 
 echo "1 - commando to start"
 exit 1
fi
``