【问题标题】:For loop - double variable using single file as inputFor 循环 - 使用单个文件作为输入的双变量
【发布时间】: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&lt;&amp;3; do $doit "$username" "$password"; done 3&lt; file

标签: bash for-loop


【解决方案1】:

对文件中的每一行执行一组操作的方法是使用while read 循环:

while read -r host something_else; do
    some_command "$host" "$something_else"
done < file

每一行都被shell分割,变量$host$something_else被设置为字段的值。

几乎总是应该使用-r 选项,因为它告诉外壳程序不要尝试对输入中的转义序列做任何聪明的事情。

【讨论】:

  • 它运行但没有遍历整个文件。它只是在第一行工作。在我正在测试的文件中,我有 25 行。没有错误或任何东西,它就退出了。
  • @user53029,你在脚本中使用set -e吗?
  • 我没有。查看我更新的帖子以显示我的脚本。我在哪里放置 set -e?
  • @user53029 如果您使用的是set -e,它可能会解释您所描述的脚本退出。我不认为格伦建议你添加它。如果在循环之前添加set -x,那么您将能够看到正在执行的命令,这可能有助于您确定发生了什么问题。
【解决方案2】:

如果您正在创建输入文件(而不仅仅是从其他地方获取),请注意您可以使用原始的两个文件:

while IFS= read -r host && IFS= read -r i <&3; do
    some_command "$host" "$i"
done < file1 3< file2

【讨论】:

  • 我也刚开始尝试这种方法,但它在第一行之后就停止了。
猜你喜欢
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 2019-09-27
  • 2023-04-09
  • 1970-01-01
  • 2021-07-25
  • 2013-03-20
相关资源
最近更新 更多