Networking

Unix and Linux network configuration. Multiple network interfaces. Bridged NICs. High-availability network configurations.

Applications

Reviews of latest Unix and Linux software. Helpful tips for application support admins. Automating application support.

Data

Disk partitioning, filesystems, directories, and files. Volume management, logical volumes, HA filesystems. Backups and disaster recovery.

Monitoring

Distributed server monitoring. Server performance and capacity planning. Monitoring applications, network status and user activity.

Commands & Shells

Cool Unix shell commands and options. Command-line tools and application. Things every Unix sysadmin needs to know.

Home » Commands & Shells, Featured

Checking Multiple Variables in Bash

Submitted by on September 19, 2017 – 10:04 am

Let’s say you have a dozen variables in your script and you need to check if they have values set. The usual approach can get a bit tedious.

if [[ -z $var1 || -z $var2 || -z $var3 ]]; then
...

This gets even worse if you need to assign some default value to any variable that is not set:
if [ -z $var1 ]; then var1=unknown; fi
if [ -z $var2 ]; then var2=unknown; fi
if [ -z $var3 ]; then var3=unknown; fi

Here’s a different approach that can save you a lot of typing:
for i in var{1..3}; do
if [ -z "$(eval echo $(echo $`eval echo "${i}"`))" ] ; then
eval "$(echo ${i})"="$(echo "unknown")"
fi; done

If you really have lots and lots of variables that require different default values, you may use a table. Parse this table to populate two arrays: one containing names of the variables and the other – their default values. Let’s say your table.txt looks like this:
variable_1,default_value
variable_two,some other default value
variable_whatever,nothing to see here

We will use it to build two arrays:
IFS=$'\n'
array_variables=($(awk -F, '{print $1}' table.txt))
array_defaults=($(awk -F, '{print $2}' table.txt))
unset IFS

Now we can read the array_variables array, check if the variables are set and, if not, assign a corresponding default value from the array_defaults array:
for ((i = 0; i < ${#array_variables[@]}; i++))
do
	if [ -z "$(eval echo $(echo $`eval echo "${array_variables[$i]}"`))" ]
	then
		eval "$(echo "${array_variables[$i]}")"="$(echo "\"${array_defaults[$i]}\"")"
	fi
done

And to check that the variables have been set:
for i in $(printf '$%s\n' ${array_variables[@]}); do eval echo ${i}; done

default_value
some other default value
nothing to see here

 

Print Friendly, PDF & Email

Leave a Reply