0

rpi のネットワーク インターフェイスをより速く設定できるように、bash スクリプトを作成しています。現在はほぼ完成しており、sed を使用して動作し、ネットワーク インターフェイスの設定方法に応じて /etc/network/interfaces ファイルのさまざまな部分を変更します。私の問題は、引用符を挿入したくない場所に引用符を挿入していることです。引用符を削除すると、値として挿入するのではなく、挿入するデータを含む変数を変数名の文字列として挿入します。

私のコードは次のとおりです(ただし、私はそれを切り詰めました)

#!/bin/bash
ANS=''
ssid=''
psk=''
file='/etc/network/interfaces'
ip=''
netmask=''
broadcast=''
gateway=''
function static {
    echo 'Will now set up Static IP'
    echo 'What IP address do you want to assign this Device?'
    echo -e '> \c'
    read ip
    echo 'What is your Networks Netmask/Subnet?'
    echo -e '> \c'
    read netmask
        echo 'What is your Networks Broadcast Address?'
        echo -e '> \c'
        read broadcast
        echo 'What is the address of your Networks Gateway?'
        echo -e '> \c'
        read gateway
    echo 'You entered the following information about your Network'
    echo ''
    echo 'Address: ' $ip
    echo 'Netmask: ' $netmask
    echo 'Broadcast: ' $broadcast
    echo 'Gateway: ' $gateway
    echo 'Is this information correct? (y/n)'
    echo -e '> \c'
        read ANS
        if [ $ANS = 'y' ]; then
        sed -i "s/^iface eth0 inet dhcp.*\$/iface eth0 inet static/" $file
        sed -i "s/^#    address.*\$/    address \"$ip\"/" $file
        sed -i "s/^#    netmask.*\$/    netmask \"$netmask\"/" $file
        sed -i "s/^#    broadcast.*\$/  broadcast \"$broadcast\"/" $file
        sed -i "s/^#    gateway.*\$/    gateway \"$gateway\"/" $file
        echo 'Static IP address has now been set up'
        start
    else
        static
    fi
}

問題はこれらの行です

        sed -i "s/^#    address.*\$/    address \"$ip\"/" $file
        sed -i "s/^#    netmask.*\$/    netmask \"$netmask\"/" $file
        sed -i "s/^#    broadcast.*\$/  broadcast \"$broadcast\"/" $file
        sed -i "s/^#    gateway.*\$/    gateway \"$gateway\"/" $file

どの挿入address "(var_address)"。私が言ったように、私はそれを挿入することができaddress $addressます。しかし、私が望むように、そうではありませんaddress (var_address)。問題を解決できるように、/ と \ を sed コマンドで " と ' と一緒に使用する方法を誰か説明してもらえませんか。

4

2 に答える 2

2

bash は のような標準変数を解決しようとはしません$/が、単純に次のようにすることができます。

sed "
    /^iface $iface/,/^$/{
        /address/s/^.*$/\taddress $ip/;
        /netmask/s/^.*$/\tnetmask $netmask/;
        /broadcast/s/^.*$/\tbroadcast $broadcast/;
        /gateway/s/^.*$/\tgateway $gateway/;

    }" -i $file

注: これは:に関する1 つのパラグラフのみ$ifaceを変更します: 最初の sed 行:空行 (またはファイルの終わり) に/^iface $iface/,/^$/{ ... }一致する行からのみ実行できるコマンド ブロックを区切ります。/^iface $iface/

また、bash で IP アドレスを操作するには、https://serverfault.com/a/461831/142978をご覧ください。

于 2013-01-20T00:20:02.483 に答える
1

何が必要かを正しく理解していれば、これはうまくいくはずです:

sed -i "s/^#    address.*\$/    address $ip/" $file
sed -i "s/^#    netmask.*\$/    netmask $netmask/" $file
sed -i "s/^#    broadcast.*\$/  broadcast $broadcast/" $file
sed -i "s/^#    gateway.*\$/    gateway $gateway/" $file
于 2013-01-19T23:16:41.833 に答える