mora mora - 2 months ago 7
Bash Question

Why "if [[ ${value} == ^[[:blank:]]*$ ]]" cannot detect empty variable?

I tried the following three codes to detects empty variable.

unset value

if [[ -z ${value} ]]; then
echo "value is judged as empty by [[ -z ]] : value = '${value}'"
fi

if [[ ${value} == ^[[:blank:]]*$ ]]; then
echo "value is judged as empty by [[ == ]] : value = '${value}'"
fi

if echo ${value} | grep -E "^[[:blank:]]*$"; then
echo "value is judged as empty by grep -E "^[[:blank:]]*$" : value = '${value}'"
fi


The results are following,

value is judged as empty by [[ -z ]] : value = ''

value is judged as empty by grep -E ^[[:blank:]]* : value = ''


Why the second one does not work? Please let me know.

Answer

Your second one is a pattern, not a regular expression. It only matches strings with at least 3 characters: ^, a single blank character, zero or more arbitrary characters, and $. To match the regular expression representing zero or more blank characters, use the =~ operator.

if [[ $value =~ ^[[:blank:]]*$ ]]; then
Comments