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

时间:2015-08-12 19:14:27

标签: bash sh virtualhost

我尝试自动添加和删除域名。我知道有一些脚本可以做到这一点,但我想学习更多的bash脚本,而不是执行我不完全理解的代码。

目前,我尝试将主机文件中的域抓取到选择列表中,然后执行删除代码以删除该行。如何仅读取包含主机名的hosts文件中的行并创建选择列表以运行删除命令?

我已经让脚本读到了hosts文件并逐行回显。

#!/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

我也想删除&#34; ip&#34;,&#34; www。&#34; &#34; .COM&#34;和冗余别名,所以列表如下所示

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

我考虑过使用一个单独的配置文件来定义域名,但对于我想要做的事情来说,这似乎有些过分。

1 个答案:

答案 0 :(得分:1)

基本上,您必须重写文件,在写入过程中过滤掉要删除的行。像

这样的东西
# untested
delDomain () {
    toDelete=$1
    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