0

I have a bash script that read a file with properties.

Properties file

param1=value1
param2=value2
param3=value3

Bash

file="./parameters.txt"

if [ -f "$file" ]
then
    echo "$file found."

    while IFS='=' read -r key value
    do
        key=$(echo $key | tr '.' '_')
        eval "${key}='${value}'"
    done < "$file"

else
    echo "$file not found."
fi

I want to check that each parameter is not empty.

if [ -z ${param1} ]
then
    echo "Param1 is empty"; exit 1
fi

I can check them through if-else but I would like to know some more dynamic way.

What would be the best way?

0

Well, the best way is always user dependent. But since you are using bash, you could use a shell parameter expansion ${!<var-name>}.
You can also use . or source to read in the file with the variables.

#!/bin/bash

file="./parameters.txt"

if [ -f "$file" ]
then
    echo "$file found."

    # Read in the values from the file.
    . "${file}"

    # Iterate over the keys of the file and test if the variable contains anything.
    while read key;
    do
        # Here comes the parameter expansion. 
        if [ -z "${!key}" ]
        then
            echo "${key} is empty"
        fi
    done <<< $(cut -d '=' -f 1  parameters.txt)
else
    echo "$file not found."
fi
  • It returns all params in one line: param1 param2 param3 is empty – user1911 Jan 13 '18 at 11:08
  • It seems there is something wrong reading in the file. What is the output of cut -d '=' -f 1 parameters.txt and wc -l parameters.txt? – Thomas Jan 13 '18 at 11:31
  • The cut result is: param1 param2 param3 and wc result is 3 – user1911 Jan 14 '18 at 9:09
  • Are the cut results newline separated or all in one line? Do you have set IFS? The cut command should return every param* result in a new line. – Thomas Jan 14 '18 at 9:18
  • Separated line by line as I set in the post. – user1911 Jan 14 '18 at 10:15
0

Try this:

#!/bin/bash

check()
{
    local file="./parameters.txt"
    local assertion var val

    while read assertion
    do
    var=${assertion/=*}
    test "${var}" != "${assertion}" || return 1
    val=${assertion#*=}
    test -n "${val}" || return 3
    done < ${file}

    return 0
}

check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.