Bash - 读取 .txt 文件并将信息存储在变量中供以后使用的脚本

Bash - Script that reads .txt file and stores the info in variables to be used later

我正在开发一个 bash 脚本,该脚本必须能够创建 "network interface profile configurations",将它们存储在任何类型的文件中(我猜是 .txt),然后,如果使用参数调用,例如:./myscript eth0 myprofile

必须执行 myprofile.txt 中的命令来配置该网络接口。

所以,现在,我正在尝试将此信息放入 .txt 文件(ip、网络掩码、网关和代理):格式示例(当然,数据可能无效!)

192.168.20.3 255.255.255.0 192.168.20.1 20.139.30.4:80

如您所见,我得到了用 "whitespaces" 分隔的此信息。我想知道这是否是 "bad practice",因为我希望脚本在给定文件名的情况下检索此信息并将其单独存储在变量中,以便我可以调用 "ifconfig, route, etc" 之类的命令。有了这个信息。

关于如何完成此操作的任何想法?

我将如何处理这个问题:

#!/bin/bash

if [[ $# != 2 ]]; then
    echo "ERROR: Usage is ./[=10=] eth-name profile-name"
    exit 1
fi

eth=
profile=

if [[ ! -f "$profile.txt" ]]; then
    echo "ERROR: $profile.txt file not found!"
    exit 1
fi

# TODO: validate $eth

ip=$(awk '{print }' "$profile.txt")
netmask=$(awk '{print }' "$profile.txt")
gateway=$(awk '{print }' "$profile.txt")
proxy=$(awk '{print }' "$profile.txt")

echo "ip: $ip"
echo "netmask: $netmask"
echo "gateway: $gateway"
echo "proxy: $proxy"

# DO whatever with $ip, $netmask, $gateway, $proxy

通过运行这个例子,我得到这个:

$ > cat myprofile.txt
192.168.20.3 255.255.255.0 192.168.20.1 20.139.30.4:80
$ > bash myscript.sh eth0 myprofile
ip: 192.168.20.3
netmask: 255.255.255.0
gateway: 192.168.20.1
proxy: 20.139.30.4:80
$ >