【发布时间】: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 betweenshandbash -
那么有没有解决办法?
-
您的原始问题询问是否可以在
sh或bash中完成;它可以在 Bash 中完成,但不能在sh中完成。它们是两种不同的外壳。 -
好吧,你的权利,我应该对此表示“如何”抱歉:)