在 Shell 脚本中为变量赋值
Assigning Values to variables in Shell scipt
我有参数文件,其中包含如下所示的数据
#host1 credentials
Host1=192.168.1.1
password=host1Password
#host2 credentials
Host2=192.168.1.2
password=host2password
我想使用 shell 脚本解析文本文件中的这些信息,并将这些值分配给变量。
$host1 = 192.168.1.1
$password1 = host1password
$host2 = 192.168.1.2
$password2 = host2password
我是 shell 脚本的新手,请帮助我实现这个。
我会使用实现数组(bash 或 ksh)的 shell,然后这样做:
hosts=()
passwords=()
# read the file, populate the arrays
while IFS="=" read -r key value; do
case $key in
password) passwords+=( "$value" ) ;;
Host*) hosts+=( "$value" ) ;;
esac
done < params
# print the contents of the arrays
for ((i=0; i < ${#hosts[@]}; i++)); do
printf "%d\t%s\t%s\n" $i "${hosts[i]}" "${passwords[i]}"
done
0 192.168.1.1 host1Password
1 192.168.1.2 host2password
我有参数文件,其中包含如下所示的数据
#host1 credentials
Host1=192.168.1.1
password=host1Password
#host2 credentials
Host2=192.168.1.2
password=host2password
我想使用 shell 脚本解析文本文件中的这些信息,并将这些值分配给变量。
$host1 = 192.168.1.1
$password1 = host1password
$host2 = 192.168.1.2
$password2 = host2password
我是 shell 脚本的新手,请帮助我实现这个。
我会使用实现数组(bash 或 ksh)的 shell,然后这样做:
hosts=()
passwords=()
# read the file, populate the arrays
while IFS="=" read -r key value; do
case $key in
password) passwords+=( "$value" ) ;;
Host*) hosts+=( "$value" ) ;;
esac
done < params
# print the contents of the arrays
for ((i=0; i < ${#hosts[@]}; i++)); do
printf "%d\t%s\t%s\n" $i "${hosts[i]}" "${passwords[i]}"
done
0 192.168.1.1 host1Password
1 192.168.1.2 host2password