【发布时间】:2016-09-01 02:30:25
【问题描述】:
我熟悉基本的 for 循环。比如这样的:
#!/bin/bash
hosts=$(< file)
for h in $hosts; do "some-command" "$h"
done
但是..我有一个使用粘贴命令创建的格式化文本文件,并排列成两列。
paste file1 file2 | column -s $'\t' -t > combinedfile
那个文件看起来像这样:
line1column1 line1column2
line2column1 line2column2
line3column1 line3column2
我需要将此文件输入一个 for 循环脚本,并一次传入每一行,使用 column1 的数据作为第一个变量,column2 的数据作为第二个变量。
类似的东西
#!/bin/bash
hosts=$(< file)
for h i in $hosts; do "some-command" "$h" "i"
done
其中“h”等于第 1 行第 1 列,“i”等于第 1 行第 2 列。这样做的正确方法是什么?
更新:在使用汤姆的方法时,我设置了我的脚本,但它在第一行运行然后退出。
这是我的设置:
#!/bin/bash
doit="/pathtocommand"
file="/pathtosourcefile"
while read -r username password; do
$doit "$username" "$password"
done < $file
想法?
更新 2:
我也想发布我的期望脚本。这是在 while 循环中运行的“命令”。
#!/usr/bin/expect -f
## Set up variables to be passed in as command line arguments
#set username [lindex $argv 0];
#set password [lindex $argv 1];
lassign $argv username password
spawn telnet 192.168.100.101 106
expect "200 PWD Server ready"
send "USER user\r"
expect "300 please send the PASS"
send "PASS password\r"
expect "200 login OK, proceed"
## Use the line below for passwords that do not have to be enclosed with quotes
send "SETACCOUNTPASSWORD $username PASSWORD $password\r"
# Use the line below for a password that must be quoted ie one that contains a $ or a ! by escaping the double quotes
#send "SETACCOUNTPASSWORD $username PASSWORD \"$password\"\r"
expect "200 OK"
send "quit\r"
interact
我过去曾在 SSH 和常规 for 循环中使用过相同的期望脚本,没有任何问题。可能是我需要修改或更改的期望脚本中的某些内容吗?
【问题讨论】:
-
脚本是否与
doit=echo一起使用? -
doit=echo 有效。所以它一定是期望脚本中它不喜欢的东西。我已经用 ssh 做到了这一点,没有问题,只是没有 telnet。不知道是不是这个问题。
-
现在尝试一些小步骤。当您的 masterscript 在没有 while 循环的情况下两次调用
$doit时,它会起作用吗?如果是这样,也许你需要为期望循环保留标准输入并尝试像@chepner 写的那样,没有host的东西:while IFS= read -r username password<&3; do $doit "$username" "$password"; done 3< file。