[SHELL: /bin/sh] For loop using variable variable names

Simple enough problem I think, I just can't seem to get it right.

The below doesn't work as intended, it's just a function defined in a much larger script:

CheckValues() {
    for field in \
        Group_ID \
        Group_Title \
        Rule_ID \
        Rule_Severity \
        Rule_Version \
        Rule_Title \
        Rule_Fix_Text; do
        if [ ! -n \$${field} ]; then
            echo "Error, ${field} undefined."
        else
            echo "\$${field}"
        fi
    done
}

The else statement won't exist once I've successfully tested it. The output I see when I run the actual script is:

# ./GEN000290-1.sh
$Group_ID
$Group_Title
$Rule_ID
$Rule_Severity
$Rule_Version
$Rule_Title
$Rule_Fix_Text
GEN000290-1: Running CMD: grep -c '^games' /etc/passwd
0
Not a finding.
GEN000290-1: Not a finding.

What I expect to see in the above is the value of those variables (Which is just a string of text assuming non-zero length).

Group_ID='V-4269-1'
Group_Title='Unnecessary Accounts, Games.'
Rule_ID='SV-4269-lr4_rule'
Rule_Severity='CAT II'
Rule_Version='GEN000290-1'
Rule_Title='The system must not have the unnecessary "games" account.'
Rule_Fix_Text='Remove the "games" account from the /etc/password file before connecting a system to the network.'

Kindly note that I need it to be /bin/sh compliant, as it'll be going across multiple Linux/Unix platforms.

This works. Note Rule_Severity is null to test:

$ cat x
#!/bin/sh

Group_ID='V-4269-1'
Group_Title='Unnecessary Accounts, Games.'
Rule_ID='SV-4269-lr4_rule'
Rule_Severity=""
Rule_Version='GEN000290-1'
Rule_Title='The system must not have the unnecessary "games" account.'
Rule_Fix_Text='Remove the "games" account from the /etc/password file before connecting a system to the network.'


CheckValues() {
    for field in \
        Group_ID \
        Group_Title \
        Rule_ID \
        Rule_Severity \
        Rule_Version \
        Rule_Title \
        Rule_Fix_Text; do
        eval var="\$${field}"
        if [ -z "$var" ]; then
            echo "Error, field [${field}] undefined."
        else
            echo "$var"
        fi
    done
}

CheckValues

exit 0
$ x
V-4269-1
Unnecessary Accounts, Games.
SV-4269-lr4_rule
Error, field [Rule_Severity] undefined.
GEN000290-1
The system must not have the unnecessary "games" account.
Remove the "games" account from the /etc/password file before connecting a system to the network.
$
1 Like

Thanks so much, that did the trick.