Bash脚本:while循环和if语句

时间:2016-09-08 05:07:14

标签: bash if-statement for-loop while-loop conditional

我正在编写一个脚本来过滤GID大于1000且GID小于或等于1000.目的是从文件中过滤出本地组和非本地组(来自AD的组)..

有一个名为groups.out的文件,其中包含组名和GID。它可以是任何顺序。下面是包含本地组,非=本地组和GID的示例文件。

1098052
1098051
domain users
fuse
gdm
haldaemon

这是我想要应用的逻辑

Read line by line from the file,
 if the line is a number then check 
       if number greater than or equal to 1000 then check
            if greater than or equal to 1000, append it to the file
        else if number less than 1000 then dump it
        else if erorr occurs append error to file and break the loop and exit

if the line is a string then check the gid of the string/group
   if number greater than or equal to 1000 then append to file
   else if gid less than 1000 then dump it
    else if error occurs append error to file and break the loop and exit
want to repeat it in the loop line by line and if anywhere the error occurs loop should break and exit the entire script

成功执行循环后,它应该打印成功,或者如果发生任何错误,它应该退出并将错误附加到文件中。 下面是我的未经烹煮的代码,其中包含许多部分。 gt或eq错误也存在许多错误。所以你可以忽略它

fileA="groups.out"
value=1000
re='[a-z]'
num='[0-9]'
while IFS= read lineA
do
group=$(getent group "$lineA" | awk -F: '{print $3}')
#   ------Don't know how to check if a number or string -----
     if [ "$group" -gt "$value" ]; then
        echo "$lineA" >> ldapgroups.out 2>> error.out
        elif [ "$group" -lt "$value" ]; then
        echo "$lineA" >> /dev/null 2>> error.out

        else
        echo " FAILED"
        exit 1
        fi

2 个答案:

答案 0 :(得分:1)

#/bin/bash
fileA="groups.out"
value=1000
num='^[0-9]+$'
while IFS= read lineA
do
    #check if the line is numbers only
    if [[ $lineA =~ $num ]];then
       echo "This is a number"
       echo $lineA
       #check if $line is greater than 1000
       if [[ $lineA -gt $value ]];then
           #write it to file named numbers.out
           echo "number is greater than 1000 writing to file"
           echo $lineA >> numbers.out
       else
           echo "less than, Skipping"
       fi
    #if its not number, its group names right? so no need to check if with regex
    else
       #do what ever u want with group names here ...
       echo "string"
       echo $lineA
    fi
# This is where you feed the file to the while loop
done <  $fileA

以下是您的脚本的更正版本。它应该让你去。 chmod +x scriptfile并使用bash scriptfile运行它或在crontab中安排它。

由于您关于如何将组名与gids匹配的信息不足以让我在脚本中将其遗漏,但您应该能够使用脚本其他部分中提供的信息来完成它。

答案 1 :(得分:0)

这看起来好像你想要两个单独的脚本。使用Awk查找特定范围内的数字很简单。

awk '!/[^0-9]/ && ($1 >= 1000)' groups.out

正则表达式选择所有数字输入行(或者更确切地说,它排除在其中任何位置包含非数字字符的行),并且数字比较要求第一个字段为1000或更多。 (Awk的默认操作是在脚本中的条件为真时打印整行,因此我们可以省略隐式{print}操作。

如果您还想将小于1000的数字提取到单独的文件中,则更改应该是显而易见的。

对于非数字值,我们可以

grep '[^0-9]' groups.out |
xargs getent |
awk -F : '$3 >= 1000 { print $3 }'

您的伪代码中的几个分支似乎是多余的。不清楚在什么情况下会发生错误,或者您在错误情况下指定的操作如何帮助您诊断错误或从错误中恢复(写入被拒绝,磁盘已满?)所以我有没有花费任何精力去尝试实施这些部件。

相关问题