Check If a Variable Exists in a List in Bash

Check if a variable exists in a list in Bash


[[ $list =~ (^|[[:space:]])$x($|[[:space:]]) ]] && echo 'yes' || echo 'no'

or create a function:

contains() {
[[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && exit(0) || exit(1)
}

to use it:

contains aList anItem
echo $? # 0: match, 1: failed

How to check dynamically that a Bash variable exists?

This function should do the job for you:

assert_var() {
if [[ -z ${!1+x} ]]; then
echo 'NOT EXISTS!'
else
echo 'EXISTS!'
fi
}

Changes are:

  • Use ${var+x} to check if a variable is unset. ${var+x} is a parameter expansion that evaluates to nothing if var is unset, and substitutes the string x otherwise. More details here.
  • Use indirect referencing of variable by name i.e. ${!1+x} instead of ${1+x}
  • Use single quotes when you are using ! in string to avoid history expansion

Testing:

FOO='123'
assert_var "FOO"
EXISTS!
assert_var "BAR"
NOT EXISTS!

How to check if a variable is set in Bash


(Usually) The right way

if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi

where ${var+x} is a parameter expansion which evaluates to nothing if var is unset, and substitutes the string x otherwise.

Quotes Digression

Quotes can be omitted (so we can say ${var+x} instead of "${var+x}") because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to x (which contains no word breaks so it needs no quotes), or to nothing (which results in [ -z ], which conveniently evaluates to the same value (true) that [ -z "" ] does as well)).

However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to the first author of this quotes explanation who is also a major Bash coder), it would sometimes be better to write the solution with quotes as [ -z "${var+x}" ], at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.

(Often) The wrong way

if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi

This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if var='', then the above solution will output "var is blank".

The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.

The distinction may not be essential in every scenario though. In those cases [ -z "$var" ] will be just fine.

checking if a string exists in an array of strings in bash

Join two test/[ commands with ||:

if [ "$build_type" = devite ] || [ "$build_type" = relite ]; then
echo "building"
fi

or use a case statement.

case $build_type in
devite|relite) echo "building" ;;
esac

If the targets are in an associative array, you can check for the existence of a key.

declare -A targets=([devite]= [relite]=)

if [[ -v targets[$build_type] ]]; then
echo "building"
fi

Check if a variable exist in an array in Bash

I solved the problem using eval



check_file_count()
{
declare -a file_list

file_list=("file1" "file2" ... "file100")

# validate cert counts
for file in ${file_list[@]}
do
eval $(printf 'file_count=$(echo ${%s[@]} | wc -w)' "${file}")

if [ ${file_count} -gt 1 ]
then
echo "[ERROR] There are more than one ${file}."
exit 1
elif [ ${file_count} -eq 0 ]
then
echo "[ERROR] ${file} does not exist."
exit 1
fi
done

}

I used echo ${file[@]} | wc -w instead of ${#file[@]} because $file is an delimited string and not an array in this case.

Bash check if array of variables have values or not

This is the correct syntax for your task

if [ -z "${!var}" ] ; then
echo $var "is not available"
else
echo $var "is available"
fi

Explanation, this method uses an indirect variable expansion, this construction ${!var} will expand as value of variable which name is in $var.

Changed check function a bit

check () {
for var in "$@"; do
[[ "${!var}" ]] && not= || not="not "
echo "$var is ${not}available"
done
}

And another variant using declare

check () {
for var in "$@"; do
declare -p $var &> /dev/null && not= || not="not "
echo "$var is ${not}available"
done
}

From declare help

$ declare --help
declare: declare [-aAfFgilnrtux] [-p] [name[=value] ...]
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.
...
-p display the attributes and value of each NAME
...

Actually all vars can be checked at once using this

check () {
declare -p $@ 2>&1 | sed 's/.* \(.*\)=.*/\1 is available/;s/.*declare: \(.*\):.*/\1 is not available/'
}


Related Topics



Leave a reply



Submit