LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Passing a list to a script (https://www.linuxquestions.org/questions/programming-9/passing-a-list-to-a-script-4175614734/)

jhdore 09-29-2017 09:02 AM

Passing a list to a script
 
Hi all,

I've got about 70 Mailman mailing lists I need to extract the members for into individual text files. I have the list names in a single file, but can't figure out how to use each line in that list as the listname for Mailman's list_members command.

I envisaged something like

Code:

for i in listnames.txt

do
/usr/lib/mailman/bin/list_members $i > $i.txt
done

but it fails with error 'No such list: listnames.txt'

This is my first foray into shell scripting, so I'm thrashing around in the dark somewhat - can anyone enlighten me?

Many thanks,
J

TenTenths 09-29-2017 09:07 AM

Try:

Code:

for i in $(cat listnames.txt)

dugan 09-29-2017 09:08 AM

Code:

while read i
do
    /usr/lib/mailman/bin/list_members $i > $i.txt
done < listnames.txt

More info:

How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?

Add "-r" to read if you need it (or if you want).

jhdore 09-29-2017 09:09 AM

Quote:

Originally Posted by TenTenths (Post 5764390)
Try:

Code:

for i in $(cat listnames.txt)

Excellent - job done!

Thanks loads.
J

David the H. 10-11-2017 06:04 AM

Quote:

Originally Posted by jhdore (Post 5764393)
Excellent - job done!

Thanks loads.
J

The solution posted by dugan is the recommended way to operate on file contents. Read the link he provided, and also this: Why you don't read lines with "for".

But to summarize, a for loop is designed to iterate over a list of words. What's happening above is that $(cat filename) is simply dumping the entire contents of the file into the loop at once, and since the $() substitution is unquoted the shell proceeds to chop it up into individual words to be processed. Depending on the contents and size of the file, this could have unexpected and deleterious consequences.

A while read loop, on the other hand, draws only one line (configurable) from the input file into the variable (or variables) for each iteration of the loop, until the file is exhausted. It is quite a bit more robust and gives you more power to control what gets read, and when, and how.

If you're truly desperate to use a for loop, however, it's also possible to use bash's mapfile built-in to read each line into an array first, then iterate over that.

Code:


mapfile -t list <inputfile.txt

for line in "${list[@]}"; do
  echo "$line"
done

mapfile puts each line of text into a separate array entry (the -t option removing the newlines at the end), and "${list[@]}", when quoted, expands them inside the loop again so that each line is treated as a separate "word".


All times are GMT -5. The time now is 07:16 AM.