Declaration

declare [-p] NAME[=VALUE] ...

When used in a function, declare makes NAMEs local variables, unless used with the -g option.

parameters

  • -a array
  • -i integer
  • -x export
  • -g make variable global when used inside function
  • -p print attributes for declared variable

Numeric Operation

$(( <math expr> ))

declare -i a=123
echo $(($a + 1)) # 124
echo $(($a < 0)) # 0
echo $(($a > 0)) # 1

Conditions

string compare

[[ "$s" = abc* || "$s" < "cdf" && ! "$s" > ghi* ]] && echo "string binary"
[[ -n "$s" || ! -z "$s" ]] && echo "string unary"

number compare

(( $a < 1 && $a == 10 || ! $a != 100 )) && echo "test number"

file

[[ -e "$f" && -w "$f" ]] && echo "test file"

unary

  • -e file exists
  • -d is directory
  • -f regular file
  • -r readable
  • -w writable
  • -x executable

binary

  • -nt newer than
  • -ot older than

Array

Declaration

declare -a arr=("hello" "bash" "array")

Expansion

See this stackoverflow answer

where

declare a=("1" "2" "3 4")

# 1 2 3 4
for x in "${a[*]}"; do
    echo "${x}"
done

# 1
# 2
# 3 4
for x in "${a[@]}"; do
    echo "${x}"
done

# 1
# 2
# 3
# 4
for x in ${a[*]}; do
    echo "${x}"
done

# same as above
for x in ${a[@]}; do
    echo "${x}"
done

passed function argument

by value

function f {
    local -a arr=("$@")
    # ...
}

declare -a arr2=(1 2 3)
f "${arr2[@]}"

by reference

function f {
    local -n arr=$1 # in zsh, the "-n"
}
declare -a arr2=(1 2 3)
f arr2

Function

Declaration

function func_name {

}

# or more portable
func_name() {

}

Variables

  • $# - number of argument passed to function