如何使用 bash 从我的主机文件中删除主机?

How can I delete hosts from my host file using bash?

我正在尝试自动添加和删除域。我知道周围有一些脚本可以执行此操作,但我想学习更多 bash 脚本而不是执行我不完全理解的代码。

目前我正在尝试将主机文件中的域抓取到 select 列表中,然后执行删除代码以删除该行。如何只读取我的主机文件中包含主机名的行并创建一个 select 列表到 运行 上的删除命令?

我已经得到脚本,它可以读取主机文件并逐行回显它。

#!/bin/bash
### Set Language
TEXTDOMAIN=virtualhost

echo "What would you like to do?"
select choice in "Add a domain" "Delete a domain" "Quit"; do
    case $choice in
        "Add a domain" ) newDomain;break;;
        "Delete a domain" ) delDomain;break;;
        "Quit" ) echo "Goodbye!"; break;;
    esac
done

function newDomain () {
    echo "Pick a name for your new domain?"
    read domain
    re="^[-a-zA-Z0-9\.]+$"
    if ! [[ $domain =~ $re ]]; then
        echo "" 
        echo 'Only numbers, letters, hyphens and periods allowed' >&2
        read -p "Do you wish to try again (Y/N)? " -n 1 -r
        echo ""
        if [[ $REPLY =~ ^[Yy]$ ]]
            then
            newDomain
        else
            echo "Goodbye!"
            break
        fi;
    else
        echo "proceed to ask for root folder name then create conf file and enable site."
    fi;
}

function delDomain () {
    while read LINE; do
    # do something with $LINE
    echo "Line: $LINE"
    done < /etc/hosts
}  

主机文件示例

127.0.0.1   localhost
127.0.1.1   Main-Server
127.0.1.1   www.site-a.com site-a.com
127.0.1.1   www.siteb.com siteb.com
127.0.1.1   www.sitec.com sitec.com
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

我还想删除 "ip"、"www."“.com”和多余的别名,因此列表如下所示

Select a domain to delete.
1) site-a
2) siteb
3) sitec

我考虑过使用单独的配置文件来定义域,但对于我尝试做的事情来说这似乎有点过分了。

本质上就是重写文件,在写入过程中过滤掉要删除的行。像

# untested
delDomain () {
    toDelete=
    tmp=$(mktemp)
    while read line; do
        if [[ $line != *$toDelete* ]]; then
            printf "%s\n" "$line"
        fi
    done < /etc/hosts > "$tmp" && mv "$tmp" /etc/hosts
}

delDomain example.com