Try this Shellcheck-clean code:
#!/bin/bash -p
# Define File
datafile=./regions-with-keys
# Create Nodes File
cat <<EOF >"$datafile"
region1 key1
region2 key2
region3 key3
EOF
# User Input
clear
echo 'PLEASE SELECT REGIONS(s) :'
echo -ne '\e[37;40m[Minimum 1 Region Required]\e[0m'
read -ra input_regions
declare -p input_regions
# Reading Regions & Keys
for input_rgn in "${input_regions[@]}" ; do
while read -r data_rgn key ; do
if [[ $data_rgn == "$input_rgn" ]] ; then
printf '%s %s\n' "$data_rgn" "$key"
fi
done <"$datafile"
done
Significant changes from the code in the question are:
- Use meaningful variable names.
- Use
declare -p input_regions
to print the contents of the array in an unambiguous way.
- Use
varname
instead of $varname
as arguments to read
. That fixes a serious bug in the original code.
- Use
printf
instead of echo
for printing variable values. See Why is printf better than echo?.
- Used
[[ ... == ...]]
instead of [ ... -eq ... ]
for comparing the region names.
[[ ... ]]
is more powerful than [ ... ]
. See Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?. Also, -eq
is for comparing integers and ==
(or, equivalently, =
) is for comparing strings.
- Did various cleanups (removed some blank lines, removed unnecessary semicolons, ...).
- The new code is Shellcheck-clean. Shellcheck identified several problems with the original code.
If you want to report incorrect input regions, try replacing the "Reading Regions & Keys" code with this:
for input_rgn in "${input_regions[@]}" ; do
# Find the key corresponding to $input_rgn
key=
while read -r data_rgn data_key ; do
[[ $data_rgn == "$input_rgn" ]] && key=$data_key && break
done <"$datafile"
if [[ -n $key ]] ; then
printf '%s %s\n' "$input_rgn" "$key"
else
printf "error: region '%s' not found\\n" "$input_rgn" >&2
fi
done