【问题标题】:Is there a way to create an associative array from a text file in bash? [duplicate]有没有办法从 bash 中的文本文件创建关联数组? [复制]
【发布时间】:2020-02-07 09:51:06
【问题描述】:

我目前正在创建一个命令列表,例如,通过说“目录安装插件名称”,我可以安装外部列表中指定的所有需要​​的插件。这个列表只是一个包含所有插件名称的 txt 文件。但是我正在努力将所有名称都放在一个关联数组中。

我试过这个:

while IFS=";" read line;
do " communtyList[ $line ]=1 " ;
done < community-list.txt;

期望的输出应该是

  • communityList[test1]=1
  • communityList[test2]=1....

它需要是一个关联数组,因为我想通过单词而不是索引来访问它。这个词将被实现为参数/参数。

例如“安装插件”而不是“1 个插件”

所以我可以这样问:

if [ ! -z "${!communtyList[$2]}" ];

更新,这里是整个代码:

#!/usr/bin/env bash
community(){
declare -A communtyList
while IFS= read line;
do communtyList[$line]=1 ;
done < community-list.txt;
#     communtyList[test1]=1
#     communtyList[test2]=1
#     communtyList[test3]=1
#     communtyList[test4]=1
if { [ $1 = 'install' ] || [ $1 = 'activate' ] || [ $1 = 'uninstall' ] || [ $1 = 'deactivate' ] ; } && [ ! -z $2 ] ;  then
     if [ $2 = 'all' ];
        then echo "$1 all community plugins....";
        while IFS= read -r line; do echo "$1  $line "; done < community-list.txt;
     elif [ ! -z "${!communtyList[$2]}" ];
        then echo "$1 community plugin '$2'....";
     else
        echo -e "\033[0;31m Something went wrong";
        echo " Plugin '$2' does not exist.";
        echo " Here a list of all available community plugins: ";
        echo ${!communtyList[@]}
        echo -e " \e[m"
    fi
else
    echo -e "\033[0;31m Something went wrong";
    if [ -z $2 ];
        then echo -e "[Plugin name] required. [community][action][plugin name] \e[m"
    else
        echo " Action '$1' does not exist.";
        echo -e " Do you mean some of this? \n install \n activate \n uninstall \e[m"
    fi
fi
echo ${!communtyList[@]}
}
"$@"

【问题讨论】:

  • sh 根本没有关联数组。也可以看看Difference between sh and bash
  • 那么有没有解决办法?
  • 您的原始问题询问是否可以在shbash 中完成;它可以在 Bash 中完成,但不能在 sh 中完成。它们是两种不同的外壳。
  • 好吧,你的权利,我应该对此表示“如何”抱歉:)

标签: bash git-bash


【解决方案1】:

要使用关联数组,您必须先声明它

declare -A communityList

然后你可以添加值

communityList[test1]=1
communityList[test2]=2
...

或者带有声明

declare -A communityList=(
    communityList[test1]=1
    communityList[test2]=2
    ...
)

【讨论】:

  • 您好,感谢您的分析。该声明已经在我的脚本中,但我没有在此处添加它。也许我应该发布整个代码。
【解决方案2】:

" communtyList[ $line ]=1 " 周围的引号表示您尝试评估第一个字符是空格的命令。您想去掉那些引号,并可能在 "$line" 周围加上引号。

也不清楚为什么你有IFS=";" - 你没有将行分成字段,所以这没有做任何有用的事情。您的输入文件中有分号吗?地点和原因;它们是什么意思?

您可能应该更喜欢 read -r,除非您特别要求 read 在输入中使用反斜杠来做奇怪的事情。

最后,按照 Ivan 的建议,您必须在尝试使用数组之前将其声明为关联类型。

把这些东西排除在外,试试

declare -A communityList

while read -r line; do
    communtyList["$line"]=1
done < community-list.txt

【讨论】:

  • 嗨,对不起,这对我不起作用 :) 它说“)语法错误:无效的算术运算符(错误标记是”但是谢谢你的回答
  • 看起来您可能使用了 Windows 编辑器。这与这个答案和常见的常见问题解答无关; stackoverflow.com/questions/39527571/…
  • 目前我正在运行 git-bash 并且代码写在一个 sh 文件中。也许我在这里混淆了我今天第一次学到的 bash/sh 命令:S
  • Bash 不在乎你如何称呼你的文件;但.sh 扩展名会误导人类读者。
  • 那应该怎么安装呢?
猜你喜欢
  • 2021-09-12
  • 2023-03-18
  • 2021-08-25
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多