A collection of useful tips in bash.
command >/dev/null # Silent all output.
command 2>&1 # Redirect errors to output (stderr to stdout).
command 2>&2 2>file # Redirect errors to stderr AND a file.
# Check if an environment variable exists.
# check_env "PATH"
function check_env() {
if [[ -z $(eval "echo \$$1") ]]; then
echo "$1 undefined"
fi
}
To single line: ($(multiline))
Element by index: ${array[N]}
First element: ${array}
Flatten: ${array[@]}
Length: ${#array[@]}
Subarray: ${array:FROM}
Subarray: ${array:FROM:TO}
# Without iterator.
for $item in "${array[@]}"; do
echo $item
done
# With iterator.
for (( i = 0; i < ${#array[@]}; i++ )); do
echo "${item[$i]}"
done
# Usage: indexof <item> <array>
# Example: indexof "hello" $array
# Return: position of ITEM in ARRAY or fail
indexof() {
local item=$1
local array=$2
local length=${#array[@]}
for (( i = 0; i < $length; i++ )); do
if [[ $item = ${array[$i]} ]]; then
echo $i
return 0
fi
done
return 1
}
Operations: $(($a + 2))
Operations (reals): $(($a + 2.0))
Range: $(seq $TO) # 0 to $TO
Range: $(seq $FROM $TO) # $(seq 0 100)
Length: ${#text}
Substring: ${text:FROM:TO}
Substring (from beginning): ${text:FROM}
Substring (from ending): ${text: -FROM} # Space is necessary !