Looping thru a list in a file
Pardon my terrible newbieness.
I have a simple procedure I need my script to perform. Loop thru a list of computer names in a file and perform a task on each. My windows script would look something like "for /F %A in (file.txt) Do" I need my bash script to parse the[list] as a file of a list. I tried set -- $variablename. #list is a file with a list of computer names. FILE=/root/list for computername in $FILE do set -- $computername echo $computername done exit 0 |
Change $FILE to `cat $FILE`
Code:
for computername in `cat $FILE` |
Maybe something like this....
#list.txt is a file with a list of computer names. file="/root/list.txt" cat ${file} | \ while read NAME do set --$NAME echo "$NAME" done |
Muzzy's didn't work but Homey's did except for the | \ part on line 3. It would just exit at that point. What does the | \ do?
It gives the output I need but with an error, unexpected end of file at the exit 0 line. |
the | is a pipe. More or less for connecting commands. In this case, "cat..." opens the file and "while read" reads the file one line at a time.
When I had | \ I just used the \ to continue the command on the next line so it looks neater. Try it without the exit 0 |
The result I am getting is the cat ${file} part, this is what is echoing 'file' to the screen. It displays the contents of 'file' then stops/hangs at the while read NAME line. I put some echos in between lines to check.
|
Here is the result when I just cat the file...
[root@mudd home]# cat /home/list.txt fred sam joe ted sue sally [root@mudd home]# Here is the script... Code:
#!/bin/bash [root@mudd home]# sh test fred sam joe ted sue sally [root@mudd home]# |
This is the result I get also, but it's not the result I want. I don't want to display the contents of the file, I want to perform an operation on each line in the file. I don't think the while statement is even being executed.
|
Ok, I guess I'm not sure just what you are trying to do with this..
set -- $NAME echo "$NAME" The echo part will list each name as it is read. |
The echo "$NAME" is just a test while I get the looping to work. I will replace it with ssh name cp this or ssh name runscript.sh ...
Add a line after this echo like echo **** to verify that it is being executed. For my purposes I don't need the cat to echo the contents, I just need a function to parse a file. |
I found a solution:
FILE="list" #Assign FILE to file list in current dir while read NAME #can't see how while read gets FILE but it does do echo $FILE ssh $NAME [command...] ssh $NAME [command...] done < list #exit reading file |
Quote:
|
I've cleaned up a few things. The FILE= statement is not needed, I took it out.
while read NAME #NAME here can be anything, used in the loop as the var. do ssh $NAME [command...] ssh $NAME [command...] done < list #exit reading file. This is where the file is found. It defaults #to pwd, the path can be used. |
All times are GMT -5. The time now is 01:40 AM. |