如果找到多个匹配项,则使用用户交互的Bash脚本

时间:2017-07-19 13:27:11

标签: bash

我有bash脚本(user_remove.sh)从文件名address_book中删除用户。 user_remove.sh执行以下操作:

1)通过命令如参数获取单个输入,并将变量知道为名称。 (名称= “$ 1”)

2)从address_book中grep该名称并重新定向输出wc命令并将结果存储在变量匹配中。

3)测试条件匹配大于1,如果是(零)回显消息将打印,“多个匹配;请选择一个删除”并与用户交互询问确认(y / n)y删除匹配的用户。

#!/bin/bash

name="$1"

matches=$(grep "$name" address_book | wc -l)


if [ "$matches" -gt 1 ]
then
    echo "More than one match; Please select one to remove"
    echo "$name Remove (y/n)?"
    read answer

    if [ "$answer" = y ]
    then
             grep -v "$name" address_book > my_tmp/address_book
             mv my_tmp/address_book address_book

    elif [ "$answer" = n ]
    then
            exit 0
    else
            echo "I could not find $name in address_book"

    fi
fi

address_book文件包含两行数据:

test abc
test xyz

示例运行:

$./user_remove.sh test
More than one match; Please select one to remove
test Remove (y/n)?y

这是我的问题:我想要这样的输出:

More than one match; Please select one to remove
test abc Remove (y/n)?y
test xyz Remove (y/n)?n

你能帮帮我吗?

由于

1 个答案:

答案 0 :(得分:1)

这是对你所拥有的一个小调整。关键是在循环之前将匹配存储在数组中。

#!/bin/bash

name="$1"

# Find all matches
matches=()
while read -r match
do
    matches+=("$match")
done < <(grep "$name" address_book)

# Loop through matches if more than one found
if [ "${#matches[@]}" -gt 1 ]
then
    for match in "${matches[@]}"
    do
        echo "More than one match; Please select one to remove"
        echo "$match Remove (y/n)?"
        read answer

        if [ "$answer" = y ]
        then
             grep -v "$match" address_book > my_tmp/address_book
             mv my_tmp/address_book address_book

        elif [ "$answer" = n ]
        then
             exit 0
        else
             echo "I could not find $name in address_book"
        fi
    done
fi

但你真正想要的是......

#!/bin/bash

name="$1"

matches=()
while read -r match
do
    matches+=("$match")
done < <(grep "$name" address_book)

if [ "${#matches[@]}" -gt 1 ]
then
    echo "More than one match; Please select one to remove"
    for match in "${matches[@]}"
    do
        echo "$match Remove (y/n)?"
        read answer

        if [ "$answer" = y ]
        then
            grep -v "$match" address_book > address_book2
            mv my_tmp/address_book address_book
        fi
    done
elif [ "${#matches[@]}" -eq 1 ]
then
    echo "I found one occurence of $name in address_book"
else
    echo "I could not find $name in address_book"
fi