Declaration
declare [-p] NAME[=VALUE] ...
When used in a function, declare makes
NAMEs local variables, unless used with the -g option.
parameters
-aarray-iinteger-xexport-gmake variable global when used inside function-pprint 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
-efile exists-dis directory-fregular file-rreadable-wwritable-xexecutable
binary
-ntnewer than-otolder than
Array
Declaration
declare -a arr=("hello" "bash" "array")
Expansion
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