gpt4 book ai didi

linux - 使用 shell 脚本打破条件循环逻辑读取 .csv 文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:10 25 4
gpt4 key购买 nike

我正在创建一个 shell 脚本来从 .csv 文件中读取用户和项目名称,并将用户添加到 config.xml 文件中。

enter image description here

下面是示例xml文件

<?xml version='1.0' encoding='UTF-8'?>
<hudson>
<authorizationStrategy>
<roleMap type="globalRoles">
<role name="Employee" pattern=".*">
<assignedSIDs>
<sid>abc</sid>
<sid>cde</sid>
<sid>user1</sid>
</assignedSIDs>
</role>
</roleMap>

<roleMap type="projectRoles">
<role name="project_a">
<permissions/>
<assignedSIDs>
<sid>abc</sid>
<sid>cde</sid>
<sid>user1</sid>
</assignedSIDs>
</role>
<role name="project_b">
<permissions/>
<assignedSIDs>
<sid>abc</sid>
<sid>cde</sid>
</assignedSIDs>
</role>
</roleMap>
</authorizationStrategy>
</hudson>

下面是代码片段

while IFS=',' read -r user projectName;
do
echo "start"
echo "userid is : $user"
echo "projectRoles is: $projectName"

#check if user is present in global role
a=$(xmlstarlet sel -t -v "/hudson/authorizationStrategy/roleMap[@type='globalRoles']/role[@name='Employee']/assignedSIDs/sid = '$user'" config.xml)
b=true
c=$(xmlstarlet sel -t -v "/hudson/authorizationStrategy/roleMap[@type='projectRoles']/role[@name='$projectName']/assignedSIDs/sid='$user'" config.xml)
d=true

if [ $a -eq $b ];
then
echo " $user is present in global roles"
#Check if the user is present in project role

if [ $c -eq $d ];
then
echo " Cannot add $user, as it is already present in $projectName "
else
echo "$user has been added to project"
echo " To step out of the script, press CTRL + c key "
fi
else
echo " $user is not present in global roles"
fi
sleep 3;
done <addExcelUser.csv

我面临的问题:1) 当我在 while 循环中使用它时,变量“c”输出为 false,但是当我在不使用 while 命令读取 .csv 文件的情况下使用它时,它显示为 true。因此,我的整个逻辑都出错了。

例如:user1存在于global role和project_a中,所以变量“a”显示为true,在if表达式中与变量b比较时,结果为true。但是即使 user1 出现在该项目角色 (project_a) 中,变量 c 也会显示 false。理想情况下它应该是真的。

我的猜测是在读取 .csv 文件并导致整个逻辑错误时循环中断的地方。

请提供您的专业知识。

最佳答案

我想出了答案。我的脚本的问题是 if [ $a -eq $b ]; 循环。

有了这个link我学会了使用 [[ ]] 来处理此类异常。

我使用了 if [[ "$a"= "$b"]] 表达式来评估导致 true 并使我的逻辑工作的条件。欢迎大家提出最佳实践的任何建议。我有很多东西要学:)

关于linux - 使用 shell 脚本打破条件循环逻辑读取 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com