Используйте массив для динамического присвоения имени переменной, затем извлеките данные массива, избегая eval - PullRequest
0 голосов
/ 09 мая 2018

Я делаю основной сценарий переписать. Частично это устраняет eval по обычным причинам, которых можно избежать. Я сталкиваюсь с проблемой поиска подходящего способа управления сценарием следующего типа.

Рассмотрим эти два eval утверждения:

eval echo '${'#${role}'[@]}' users
loc_NagiosUsersAll+=($( eval echo '${'${role}'[@]}' " " ))

Первый выводит на экран количество пользователей в рамках данной роли. Второй добавляет всех этих пользователей в больший массив.

Роль - быть тем, кем оценивается текущая роль. Давайте назовем это read_only. Мы могли бы написать это первое утверждение следующим образом:

printf "${#read_only[@]} users"

Я испробовал десятки комбинаций скобок, кавычек и различной акробатики, чтобы бросить вызов и заставить их работать.

Вот версия эха-эха (использующая одну из реальных ролей) для сравнения:

$ echo echo '${'#${role}'[@]}' users
echo ${#authorized_for_all_host_commands[@]} users
$ echo ${#authorized_for_all_host_commands[@]} users
6 users
$ eval echo '${'#${role}'[@]}' users
6 users

Мне удалось отбросить все остальные операторы eval, но этот тип вырыт как галочка.

Итак, как я могу сделать это более безопасно, чем с помощью eval?

Еще код ...

declare -a NagiosUserRolesAll=( authorized_for_read_only 
                            authorized_for_all_services 
                            authorized_for_all_hosts 
                            authorized_for_system_information 
                            authorized_for_configuration_information 
                            authorized_for_system_commands 
                            authorized_for_all_service_commands 
                            authorized_for_all_host_commands ) 

function func_NagiosUserDataGet(){ # was load_data_tables 
    local -a loc_NagiosUsersAll="" 
    printf "Loading users into the different tables.  \n" 
    for role in "${NagiosUserRolesAll[@]}" 
        do 
            declare -ag $role="($( cat ${svnFilePath} | sed -n "s/${role}=//p" | sed  's/,/ /g' ))"
            declare -n ref="${role}" # copy the reference, not the contents of the array 
            printf "The role ${role} has ${#ref[@]} users.  \n" 
            loc_NagiosUsersAll+=(${ref[@]}) 
            loc_NagiosUsersAll+=" " 
        done 
    printf "Creating list of unique users.  \n" 
    NagiosUsersAllClean=($( echo ${loc_NagiosUsersAll[@]} | tr ' ' '\n' | 
sort -u )) 
    printf "Total users:  ${#NagiosUsersAllClean[@]}.  \n" 
} 

function func_NagiosUsersShow(){ # was show_all_users 
    if [[ "${svnFileExists}" == '1' ]] ; then 
        printf "You'll need to checkout a cgi.cfg file first.  \n" 
        return 1 
    fi 
    printf "\nThese are the roles with their users.  \n\n"
    for role in "${NagiosUserRolesAll[@]}" 
        do 
            # declare -ng ref="${role}" # copy the reference, not the contents of the array 
            printf "These users are in ${const_TextRed}${role}" 
            printf "${const_TextPlain}:  " 
            printf "${const_TextGreen}" 
            # printf "${ref[@]}  \n" # FAILS 
            printf "${ref[*]}  \n" # ALSO FAILS (prints one user for each role)
            # eval echo '${'${role}'[@]}' # WORKS 
            printf "${const_TextPlain}  \n" 
        done 
    printf "\nNow for a list of unique users.  \n\n"
    func_EnterToContinue
    printf "Unique users list:  \n" 
    for i in "${!NagiosUsersAllClean[@]}" 
        do 
            printf "$i:  ${NagiosUsersAllClean[$i]}  \n" 
        done 
    func_EnterToContinue
} 

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Окончательная рабочая версия двух функций выглядит следующим образом. Я не понимаю, почему для строк printf требовалось такое точное форматирование, но вот оно у вас.

function func_NagiosUserDataGet(){ # was load_data_tables 
    local -a loc_NagiosUsersAll="" 
    printf '%s\n' "Loading users into the different tables.  " 
    for role in "${NagiosUserRolesAll[@]}" 
        do 
            declare -ag "${role}"="($( cat ${svnFilePath} | sed -n "s/${role}=//p" | sed  's/,/ /g' ))" 
            declare -n ref="${role}" # copy the reference, not the contents of the array 
            printf "The role ${role} has ${#ref[@]} users.  %s\n" 
            loc_NagiosUsersAll+=("${ref[@]}") 
            loc_NagiosUsersAll+=(" ") 
        done 
    printf '%s\n' "Creating list of unique users.  " 
    NagiosUsersAllClean=($( echo "${loc_NagiosUsersAll[@]}" | tr ' ' '\n' | sort -u )) 
    printf "There are ${#NagiosUsersAllClean[@]} total users.  %s\n" 
} 

function func_NagiosUsersShow(){ # was show_all_users 
    if [[ "${svnFileExists}" == '1' ]] ; then 
        printf '%s\n' "You'll need to checkout a cgi.cfg file first.  " 
        return 1 
    fi 
    printf '%s\n' "" "These are the roles with their users.  " ""
    for role in "${NagiosUserRolesAll[@]}" 
        do 
            declare -n ref="${role}" # copy the reference, not the contents of the array 
            printf "The role ${const_TextRed}${role}${const_TextPlain} has these ${#ref[@]} users:  %s" 
            printf "${const_TextGreen} %s\n" 
            printf '%s ' "${ref[@]} " 
            printf "${const_TextPlain} %s\n" 
            printf "%s\n" 
        done 
    read -p "Now, would you like to see a list of unique users?  (y/N)  " 
    if  func_YesOrNo "${REPLY}" 
                then 
                    printf '%s\n' "Unique users list:  " 
                    for i in "${!NagiosUsersAllClean[@]}" 
                        do 
                            printf "$i:  ${NagiosUsersAllClean[$i]}  %s\n" 
                        done 
                    func_EnterToContinue 
                else 
                    return 0  
            fi 
} 
0 голосов
/ 10 мая 2018

В bash 4.3 или более поздней версии вы можете объявить переменную как ссылку на другую переменную, сказав declare -n varref. Вот пример кода:

#!/bin/bash

declare -a read_only=(Alice Bob Charlie)
declare -a authorized_for_all_host_commands=(Dan Emma Fred George Harry Irene)
declare -a loc_NagiosUsersAll

declare -n role="read_only"
echo ${#role[@]} users
# yields "3 users"
loc_NagiosUsersAll+=(${role[@]})

declare -n role="authorized_for_all_host_commands"
echo ${#role[@]} users
# yields "6 users"
loc_NagiosUsersAll+=(${role[@]})

echo ${#loc_NagiosUsersAll[@]} users
# yields "9 users"
echo ${loc_NagiosUsersAll[@]}
# yields "Alice Bob Charlie Dan Emma Fred George Harry Irene"

Надеюсь, это поможет.

[Изменено] Следующий код является модифицированной версией, основанной на вашем последнем сообщении.

declare -a NagiosUserRolesAll=( authorized_for_read_only
                            authorized_for_all_services
                            authorized_for_all_hosts
                            authorized_for_system_information
                            authorized_for_configuration_information
                            authorized_for_system_commands
                            authorized_for_all_service_commands
                            authorized_for_all_host_commands )

function func_NagiosUserDataGet(){ # was load_data_tables
    local -a loc_CaptureUsersPerRole=""
    local -a loc_NagiosUsersAll=""
    printf "Loading users into the different tables.  \n"
    for role in "${NagiosUserRolesAll[@]}"; do
        declare -a $role="($( cat ${svnFilePath} | sed -n "s/${role}=//p" | sed  's/,/ /g' ))"
        printf "These users have the role ${role}:  "

        declare -n ref=$role         # copy the reference, not the contents of the array
        printf "${#ref[@]} users  \n"

        loc_NagiosUsersAll+=(${ref[@]})
#       loc_NagiosUsersAll+=" "
    done
    printf "Creating list of unique users.  \n"
    NagiosUsersAllClean=($( echo ${loc_NagiosUsersAll[@]} | tr ' ' '\n' | sort -u ))
    printf "Total users:  ${#NagiosUsersAllClean[@]}.  \n"
}

[Отредактировано 12 мая] Дело в том, что назначение ссылки должно появляться в синтаксисе declare -n. Иначе это даст неожиданный результат. Вот пример:

declare -a arys=(ary_a ary_b ary_c)
declare -a ary_a=(a1 a2 a3)
declare -a ary_b=(b1 b2 b3)
declare -a ary_c=(c1 c2 c3)

# test 1
for role in "${arys[@]}"; do
    declare -n ref="$role"
    echo "${ref[@]}"
done
# => works properly

# test 2
for role in "${arys[@]}"; do
    declare -n ref
    ref="$role"
    echo "${ref[@]}"
done
# => does not work correctly

[Отредактировано 15 мая] Вот модифицированная версия, которая должна работать:

declare -a NagiosUserRolesAll=( authorized_for_read_only
                            authorized_for_all_services
                            authorized_for_all_hosts
                            authorized_for_system_information
                            authorized_for_configuration_information
                            authorized_for_system_commands
                            authorized_for_all_service_commands
                            authorized_for_all_host_commands )

function func_NagiosUserDataGet(){ # was load_data_tables
    local -a loc_NagiosUsersAll=""
    printf "Loading users into the different tables.  \n"
    for role in "${NagiosUserRolesAll[@]}"
        do
            declare -ag $role="($( cat ${svnFilePath} | sed -n "s/${role}=//p" | sed  's/,/ /g' ))"
            declare -n ref="${role}" # copy the reference, not the contents of the array
            printf "The role ${role} has ${#ref[@]} users.  \n"
            loc_NagiosUsersAll+=(${ref[@]})
            loc_NagiosUsersAll+=" "
        done
    printf "Creating list of unique users.  \n"
    NagiosUsersAllClean=($( echo ${loc_NagiosUsersAll[@]} | tr ' ' '\n' |
sort -u ))
    printf "Total users:  ${#NagiosUsersAllClean[@]}.  \n"
}

function func_NagiosUsersShow(){ # was show_all_users
    if [[ "${svnFileExists}" == '1' ]] ; then
        printf "You'll need to checkout a cgi.cfg file first.  \n"
        return 1
    fi
    printf "\nThese are the roles with their users.  \n\n"
    for role in "${NagiosUserRolesAll[@]}"
        do
            declare -ng ref="${role}" # copy the reference, not the contents of the array
            printf "These users are in ${const_TextRed}${role}"
            printf "${const_TextPlain}:  "
            printf "${const_TextGreen}"
            # printf "${ref[@]}  \n" # FAILS
            printf "${ref[*]}  \n" # => should work
            # eval echo '${'${role}'[@]}' # WORKS
            printf "${const_TextPlain}  \n"
        done
    printf "\nNow for a list of unique users.  \n\n"
    func_EnterToContinue
    printf "Unique users list:  \n"
    for i in "${!NagiosUsersAllClean[@]}"
        do
            printf "$i:  ${NagiosUsersAllClean[$i]}  \n"
        done
    func_EnterToContinue
}
...