Ruchir Bharadwaj
Ruchir Bharadwaj

Reputation: 1272

Check config files for key value pair and prompt message if some values are not set

I would like to read a configuration file and check all the key value pairs and in case some values are not set prompt user for those particular key value is not set.

I am trying to achieve this by sourcing in the configuration file and then checking the keys as appropriate:-

 if [ ! -r "${file}" ]; then
    echo "Lfile is not readable kindly verify"
  elif [ ! -r "${file1}"]; then
    echo "file1 is not readable kindly verifry"
  elif [ -z $key ];then
    echo "KEY_ is not set"
 elif.....

   .....

fi 

however in this case the issue I am having is, it will list all the key value paris and move further in script however I want it to abort in case some values are not set and prompt that value on terminal

if I use exit in between for example:-

if [ ! -r "${file}" ]; then
    echo "Lfile is not readable kindly verify"
    exit
  elif [ ! -r "${file1}"]; then
   echo "file1 is not readable kindly verify"
   exit

it will only prompt one undefined value at a time.

So my question is how I can enable my script to check the entire key value pair and list the all keys which are not set.

Upvotes: 1

Views: 368

Answers (2)

anubhava
anubhava

Reputation: 785631

You can write your script like this:

if [ ! -r "${file}" ]; then
    echo "Lfile is not readable kindly verify"
    exit 1
elif [ ! -r "${file1}"]; then
   echo "file1 is not readable kindly verify"
   exit 1
fi

# list of all keys you want to check for
allKeys=("key1" "key2" "key3" "key4")
missing=()
for k in ${allKeys[@]}; do
    [[ -z "${!k}" ]] && missing+=($k)
done

if [[ ${#missing[@]} -gt 0 ]]; then
    printf "Missing keys are: %s\t" "${missing[@]}"
    echo ""
    exit 1
fi

Upvotes: 2

Andy Ray
Andy Ray

Reputation: 32076

You could use an array

arr=()

key1="hi"
key2="bye"
arr+=($key1)
arr+=($key2)

echo ${arr[@]}

Upvotes: 0

Related Questions