使用数组动态分配变量名称,然后提取数组数据,同时避免使用eval

时间:2018-05-09 09:26:37

标签: arrays bash command eval substitution

我正在重写一个主要的脚本。其中一部分是删除eval,因为通常的原因可能会避免eval。我在找到管理以下场景类型的可行方法时遇到了麻烦。

考虑这两个eval语句:

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

第一个用于筛选给定角色中的用户数。第二个将所有这些用户添加到更大的阵列中。

角色应该是当前评估的角色。我们称之为read_only。我们可以写下第一个语句如下:

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

我已经尝试了几十种括号,引号和各种杂技的组合来放弃eval并让它们起作用。

这是echo echo版本(使用其中一个实际角色)进行比较:

$ 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 :(得分:1)

使用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"
}

[5月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

[5月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
}

答案 1 :(得分:0)

这两个功能的最终工作版本如下。我不清楚为什么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 
}