Bash: How to Check if Variable Exists in a List


Often you may want to use Bash to check if a variable exists in a list.

You can use the following syntax to do so:

[[ " $my_list " =~ " $my_var " ]] && echo 'Exists' || echo 'Does Not Exist'

This particular example will check if the value stored in the variable named $my_var exists in the list named $my_list and return one of the following strings as a result:

  • “Exists”
  • “Does Not Exist”

The following example shows how to use this syntax in practice.

Example: How to Check if Variable Exists in List in Bash

Suppose we create a variable in Bash named my_var that contains the following value:

  • Mavs

Suppose that we would like to check if this variable exist in a list named my_list that contains the names of various basketball teams.

We can use the following syntax to do so:

my_var="Mavs"
my_list="Hawks Nets Mavs Celtics Lakers Kings"

[[ " $my_list " =~ " $my_var " ]] && echo 'Exists' || echo 'Does Not Exist'

The following screenshot shows how to use this syntax in practice:

Bash check if variable exists in list

Notice that this returns “Exist” since the value stored in the my_var variable does indeed exist in the list name my_list.

Suppose that our my_var variable contained the team name “Rockets” instead.

We can use the following syntax to check if this variable exists in the list of team names:

my_var="Rockets"
my_list="Hawks Nets Mavs Celtics Lakers Kings"

[[ " $my_list " =~ " $my_var " ]] && echo 'Exists' || echo 'Does Not Exist'

The following screenshot shows how to use this syntax in practice:

Notice that this returns “Does Not Exist” since the value stored in the my_var variable indeed does not exist in the list name my_list.

Feel free to replace the strings in the echo statements with any strings that you’d like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Select Random Element from an Array
Bash: How to Split a String into Multiple Variables
Bash: How to Trim Trailing Whitespace from a Variable

Leave a Reply