4

There have been several situations where I have had some output such as

thing1 thing2 thing3 

But have wanted to do something like:

*command* thing1 *command* thing2 *command* thing3 

An example of this would be: let's say I want to kill all screen sessions. Is there any way I can get one command to use somthing like:

screen -ls 

which might result in

88.mine (detached) 22.mine (detached) 

Can I do something that would result in all of the possible commands such as this:

screen -S 88.mine test -X screen -S 88.mine test -X 

in one fell swoop?

2 Answers 2

8

Sure, just use read:

while read -r line; do command "$line" done < file 

In your more specific screen example, you need to remove the remaining text:

while read -r session _; do screen -S "$session" test -X done < file 
0

There are a couple of ways of reading a newline separated list as input. The one you choose will depend on what exactly you are trying to do, but here are some simple examples:

  • while/read

    $ printf "Tom\nDick\nHarry\n" | while read name; do echo "Hi $name"; done Hi Tom Hi Dick Hi Harry 
  • for

    $ for name in $(printf "Tom\nDick\nHarry\n"); do echo "Hi $name"; done Hi Tom Hi Dick Hi Harry 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.